Get a row from the middle of a row

I have a coded string from which I would like to get the value. I understand that I can do some string manipulation ( IndexOf, LastIndexOfetc.) to get it out 12_35_55_219of the line below, but I was wondering if there is a cleaner way to do this.

"AddedProject[12_35_55_219]0"
+5
source share
5 answers

If you can be sure of the format of the string, then there are several possibilities:

My favorite is to create a very simple tokenizer:

string[] arrParts = yourString.Split( "[]".ToCharArray() );

Since the line has a regular format, arrParts will have three entries, and the part you are interested in will be arrParts[1].

If the format of the string changes, you will have to use other methods.

+6

, , , Guffa.

, , , IndexOf LastIndexOf , Fredrik

string GetMiddleString(string input, string firsttoken, string lasttoken)
{
    int pos1 = input.IndexOf(firsttoken) + 1; 
    int pos2 = input.IndexOf(lasttoken); 
    string result = input.Substring(pos1 , pos2 - pos1);
    return result
}

, .

+5

, . , :

string input = "AddedProject[12_35_55_219]0";
string part = Regex.Match(input, @"\[[\d_]+\]").Captures[0].Value;
+4

, , IndexOf LastIndexOf . .

+1

Wagner Silveira GetMiddleString

string GetMiddleString(string input, string firsttoken, string lasttoken)
    {
        int pos1 = input.ToLower().IndexOf(firsttoken.ToLower()) + firsttoken.Length;
        int pos2 = input.ToLower().IndexOf(lasttoken.ToLower());            
        return input.Substring(pos1 , pos2 - pos1);
    }

string data = "AddedProject[12_35_55_219]0";
string[] split = data.Split("[]".ToCharArray());
rtbHelp.Text += GetMiddleString(data, split[0], split[2]).Trim("[]".ToCharArray());//print it to my C# winForm RichTextBox Help
0

All Articles