且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在c#中获取字符串的一部分

更新时间:2023-02-21 17:46:58

试试这个:

  string  [] parts = yourStr.Split(' :'); 
string a = parts [ 1 ]。Trim();
string b = parts [ 3 ]。修剪();


如果你有字符串的长度并通过子字符串开始索引,你可以很容易地得到它:



  string  myStr =  这是测试; 
// string.Substring(int startInde,int length);
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 = 字典<字符串,>
();
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 over

modellist