如何在c#中获取字符串的一部分 [英] How to get part of a string in c#
本文介绍了如何在c#中获取字符串的一部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
大家好
以下是记事本中的字符串
PUCID:0000000000000002:LastPBLine:7
现在我想提取数字并分配给变量。
例如a = 0000000000000002
和b = 7
请告诉我怎么做
解决方案
试试这个:
string [] parts = yourStr.Split(' :');
string a = parts [ 1 ]。Trim();
string b = parts [ 3 ]。修剪();
如果你有字符串的长度并通过子字符串开始索引,你可以很容易地得到它:
string myStr = 这是测试< /跨度>;
// string.Substring(int startInde,int length);
< span class =code-keyword> string myPart = myStr .Substring( 2 , 7 ); // 结果为:s is te
如果你有一个specefic字符:
string myStr = this * is * test;
string [] myPart = myStr.Split(' *'跨度>);
// 结果是:
// myPart [0] =this;
// myPart [1] =是;
// myPart [2] =test;
您可以尝试的最简单的方法如下
string text = System.IO.File.ReadAllText( @ C:\ Users \ UserName \ Document'\\ work \ test.txt);
string [] arr = text.Split(' :跨度>);
列表< mymodel> modellist = new List< mymodel>();
字典<字符串,> d_list = 新字典<字符串,< span class =code-keyword>> ();
for ( int i = 0 ; i < arr.Length; i = i + 2 )
{
MyModel mm = new MyModel();
mm.FirstNum = arr [i];
mm.SecondNum = arr [i + 1 ];
modellist.Add(mm);
}
< / mymodel > < / mymodel >
现在您可以轻松迭代modellist
Hi all
Below is my string in a notepad
PUCID: 0000000000000002:LastPBLine: 7
Now i want to extract the number's and assign to variables.
e.g. a=0000000000000002
and b=7
Please tell me how to do this
解决方案
Try this:
string[] parts = yourStr.Split(':'); string a = parts[1].Trim(); string b = parts[3].Trim();
you can get it easily if you have lenth of string and start index by substring:
string myStr ="this is test"; //string.Substring(int startInde,int length); string myPart = myStr .Substring(2,7);//the result is:"s is te"
and if you have a specefic character:
string myStr ="this*is*test"; string[] myPart = myStr.Split('*'); //the result is: //myPart[0] = "this"; //myPart[1] = "is"; //myPart[2] = "test";
The simplest way which you can try is as follows
string text = System.IO.File.ReadAllText(@"C:\Users\UserName\Documents\Work\test.txt"); string[] arr=text.Split(':'); List<mymodel> modellist = new List<mymodel>(); Dictionary<string,> d_list = new Dictionary<string,>(); for (int i = 0; i < arr.Length; i = i + 2) { MyModel mm = new MyModel(); mm.FirstNum = arr[i]; mm.SecondNum = arr[i + 1]; modellist.Add(mm); } </mymodel></mymodel>
now you can easily iterate overmodellist
这篇关于如何在c#中获取字符串的一部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文