Substring IndexOf in c#

14,586

Solution 1

When call Substring you should not start from 0, but from the index found:

  String name = "texthere^D123456_02";

  int indexTo = name.LastIndexOf('_');

  if (indexTo < 0)
    indexTo = name.Length;

  int indexFrom = name.LastIndexOf('^', indexTo - 1);

  if (indexFrom >= 0)
    name = name.Substring(indexFrom + 1, indexTo - indexFrom - 1);

Solution 2

string s = "texthere^D123456_02";
            string result= s.Substring(s.IndexOf("^") + 1);//Remove all before
            result = result.Remove(result.IndexOf("_"));//Remove all after

Solution 3

Use the String.Split method :

    var split1 = name.Split('^')[1];
    var yourText = split1.Split('_')[0];

Or you could use RegExp to achieve basically the same.

Solution 4

An alternative to what's already been suggested is to use regex:

string result = Regex.Match("texthere^D123456_02", @"\^(.*)_").Groups[1].Value; // D123456

Solution 5

Your easiest solution would be to split the string first, and then use your original solution for the second part.

string name = "texthere^D123456_02";
string secondPart = name.Split('^')[1]; // This will be D123456_02

Afterwards you can use the Substring as before.

Share:
14,586
Desutoroiya
Author by

Desutoroiya

Updated on July 21, 2022

Comments

  • Desutoroiya
    Desutoroiya almost 2 years

    I have a string that looks like this: "texthere^D123456_02". But I want my result to be D123456.

    this is what i do so far:

    if (name.Contains("_"))
    {
    name = name.Substring(0, name.LastIndexOf('_'));
    }
    

    With this I remove at least the _02, however if I try the same way for ^ then I always get back texthere, even when I use name.IndexOf("^")

    I also tried only to check for ^, to get at least the result:D123456_02 but still the same result.

    I even tried to name.Replace("^" and then use the substring way I used before. But again the result stays the same.

    texthere is not always the same length, so .Remove() is out of the question.

    What am I doing wrong?

    Thanks

  • Steve
    Steve about 8 years
    While more complex this is the only approach that doesn't create unnecessary and temporary strings
  • nkoniishvt
    nkoniishvt about 8 years
    Groups[0] returns the whole match, it should be Groups[1]
  • Green Falcon
    Green Falcon over 7 years
    are you sure about the answer?