ahsteele
ahsteele

Reputation: 26514

Retrieve string from the middle of a string

I have a coded string that I'd like to retrieve a value from. I realize that I can do some string manipulation (IndexOf, LastIndexOf, etc.) to pull out 12_35_55_219 from the below string but I was wondering if there was a cleaner way of doing so.

"AddedProject[12_35_55_219]0"

Upvotes: 5

Views: 7618

Answers (5)

123iamking
123iamking

Reputation: 2703

Here is a improvement from Wagner Silveira's 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);
    }

And here how you use it

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

Upvotes: 0

Wagner Silveira
Wagner Silveira

Reputation: 1626

So in summary, if you have a pattern that you can apply to your string, the easiest is to use regular expressions, as per Guffa example.

On the other hand you have different tokens all the time to define the start and end of your string, then you should use the IndexOf and LastIndexOf combination and pass the tokens as a parameter, making the example from Fredrik a bit more generic:

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
}

And this is assuming that your tokens only happens one time in the string.

Upvotes: 6

Chris
Chris

Reputation: 6780

There are two methods which you may find useful, there is IndexOf and LastIndexOf with the square brackets as your parameters. With a little bit of research, you should be able to pull out the project number.

Upvotes: 1

Guffa
Guffa

Reputation: 700840

That depends on how much the string can vary. You can for example use a regular expression:

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

Upvotes: 4

kmontgom
kmontgom

Reputation: 1429

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

My favorite is to create a very simple tokenizer:

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

Since there is a regular format to the string, arrParts will have three entries, and the part you're interested in would be arrParts[1].

If the string format varies, then you will have to use other techniques.

Upvotes: 7

Related Questions