C # subscript

I have a line that looks like this: "FirstName||Sam LastName||Jones Address||123 Main ST ..." (100 other values)

I want to find only Sam and Jones from the whole line.

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

Does anyone know how I can do this?

OPTIONAL - I think I forgot to mention a couple of things.

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

So, if I count the number of characters that will not help me, the reason may be more elements except just the name and the name.

+6
source share
5 answers

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 his demo here .

+7
source

I think this may work better than the .Split approach. If you have || between "Sam" and "LastName", then you probably want .Split. Be that as it may, it could 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); 
+4
source

I would split the line twice twice into "", and then again into || to get the first and last name values

 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]; } } 
+1
source
 str = Str.Split("||")[1].split(" ")[0] //Sam str = Str.Split("||")[2].split(" ")[0] // Jones 
0
source

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 before the first letter to "lastname" the same goes for the surname, you just switch the name with the name and surname with the address

edit: my error ... this is not substring.(indexOf... but it

originalString.Substring(origianlString.IndexOf("FirstName) + 11, (originalString.IndexOf("LastName") - originalString.IndexOf("FirstName") + 11) and when searching for a surname it is not + 11, but 10, because "LastName".Length + + "||".Length = 10

0
source

Source: https://habr.com/ru/post/887239/


All Articles