c# substring indexof

匿名 (未验证) 提交于 2019-12-03 08:46:08

问题:

i have a string which looks like this - "FirstName||Sam LastName||Jones Address||123 Main ST ..." (100 more different values)

I want to find only Sam and Jones from the entire string.

so string firstname = originalstring.substring ... etc.

Does anyone know how I can do this?

ADDITION - I think i forgot to mention couple of things.

FirstName||Sam\r\n MiddleName||\r\n LastName||Jones\r\n .... 

So now if i count the number of characters that wont help me, cause could need more items other than just firstname and lastname.

回答1:

Use Regular expressions:

string myString = "FirstName||Sam LastName||Jones Address||123 Main ST..."; string pattern = @"FirstName\|\|(\w+) LastName\|\|(\w+) "; Match m = Regex.Match(myString, pattern); string firstName = m.Groups[1].Value string lastName = m.Groups[2].Value; 

See its Demo here.



回答2:

I think this might work better than the .Split approach. If you had || between 'Sam' and 'LastName' then you'd certainly want to .Split. As it is, this might be better.

    string inStr = "FirstName||Sam LastName||Jones Address||123 Main ST ";     int fStart = inStr.IndexOf("FirstName") + "FirstName".Length + "||".Length;     int fEnd = inStr.IndexOf(" LastName");      string FirstName = inStr.Substring(fStart, fEnd - fStart); 


回答3:

I would split the string twice once on " " and then again on || to get the values of first and last name

string [] ary = s.Split(" "); string [] key; string firstname; string lastname; foreach (string val in ary ) {     key = val.Split("||");     if ( key[0] == "FirstName") {          firstname = key[1]; } if ( key[0] == "LastName") {    lastname = key[1]; } } 


回答4:

str = Str.Split("||")[1].split(" ")[0] //Sam str = Str.Split("||")[2].split(" ")[0] // Jones 


回答5:

something like this string firstname = originalstring.substring(indexof("FirstName") + 11, ((indexof("LastName) - indexof("FirstName") + 11 )

this way you get to the first letter after || and till the first letter before "lastname" the same goes for surname you just switch firstname with lastname and lastname with adress

edit: my fault... it's not substring.(indexOf... but it's

originalString.Substring(origianlString.IndexOf("FirstName) + 11, (originalString.IndexOf("LastName") - originalString.IndexOf("FirstName") + 11) and when looking for last name it's not + 11 but 10 because "LastName".Length + + "||".Length = 10



文章来源: c# substring indexof
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!