views:

97

answers:

4

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"
+5  A: 

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.

kmontgom
+1 for not suggesting regular expressions.
Brian
... otherwise I'd have two problems, right ;)
kmontgom
@Brian: Why do you fear regular expressions?
Guffa
@Guffa - One reason to avoid them is they are a bear to maintain, and not one person in 10 understands them. It's a maintenance headache.
Randy Minder
+3  A: 

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;
Guffa
A: 

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.

Chris
+2  A: 

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.

Wagner Silveira