Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# substring indexof

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.

like image 824
refer Avatar asked May 03 '11 21:05

refer


3 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 its Demo here.

like image 190
Aliostad Avatar answered Sep 25 '22 00:09

Aliostad


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);
like image 39
Rob P. Avatar answered Sep 25 '22 00:09

Rob P.


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];
}
}
like image 43
Avitus Avatar answered Sep 25 '22 00:09

Avitus