refer
refer

Reputation: 81

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.

Upvotes: 8

Views: 46472

Answers (5)

Avitus
Avitus

Reputation: 15968

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];
}
}

Upvotes: 1

Ivan Crojach Karačić
Ivan Crojach Karačić

Reputation: 1911

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

Upvotes: 0

Aliostad
Aliostad

Reputation: 81700

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.

Upvotes: 8

Rob P.
Rob P.

Reputation: 15091

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);

Upvotes: 5

rerun
rerun

Reputation: 25505

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

Upvotes: 0

Related Questions