Question

i've got this error while i'm using the substring method.

i'm trying to execute this very simple code:

string bla = selected.Substring((selected.IndexOf('(')+1), (selected.Length-1))

selected value could be blabla(bla) and i want to get just the 'bla' inside the brackets...

edit: i want to know if there is a way to do everything on one line, thank for all the answers edit2: the right answer is

selected.Substring((selected.IndexOf('(') + 1), (selected.Length - selected.IndexOf('(') - 2))

thank to sinatr, i did a stupid mistake

Was it helpful?

Solution

It's not that simple. The second parameter of String.Substring is the length not the end-index. You also have to to check if the index is >= 0 and use String.IndexOf with the overload that takes the start-index to find the correct end-index:

string selected = "blabla(bla)";
string bla = selected;
int index = selected.IndexOf('(');
if(index++ >= 0) // index++ because you want to omit (
{
    int endIndex = selected.IndexOf(')', index); // index is start-index to find )
    if (endIndex >= 0)
    {
        bla = selected.Substring(index, endIndex - index); // endIndex - index -> Length
    }
}

OTHER TIPS

This should work given the simple scenario you presented:

string bla = selected.Split(new char[] { '(', ')' })[1];

You could also do that with regex, although it's kinda heavy artillery for that kind of a task ;)

string pattern = @"(?<=\()\w+(?=\))";
string input = "BLALBALBLA(BLA)";
string output;
Match match = Regex.Match(input, pattern);
if(match.Success)
{
    output = match.Value;
}

according to Substring, thesecondparameter is Length of the substring, then you may code ASSUMING the string is well formatted, not empty..

int l_a = selected.IndexOf('(') + 1;
int l_b = selected.IndexOf(')');
string bla = selected.Substring(l_a,l_b-l_a)

Here your problem solved with regex. Will match anything behind first ( except the last char.

string bla = "blabla(bla)";

Match match = Regex.Match(bla, @"\((.*).");
if (match.Success)
{
    bla = match.Groups[1].Value;
}

and if you are sure it matches you can do it as oneliner:

bla = Regex.Match(bla, @"\((.*).").Groups[1].Value;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top