IndexOf different results with input with spaces

Viewed 105

I'm facing a little problem when getting all the strings between two delimiters. As I saw on other related questions, (one of) the way to get characters between two delimiters is as follow: Given some string, in my example here "void foo(int a, int b) {", I want to get every char between the parentheses. Using:

String parameters = currLine.trim().substring(currLine.indexOf("("),
                    currLine.indexOf(")")-1);

Where currLine is of course "void foo(int a, int b) {". Now everything works perfectly, since I get the "int a, int b" strings. The problem is that with a string like the following:

    void                    foo                   (    int a      ,      String      b              )               {                 

I get that: parameters = "nt a , String b ) " And I have no idea how to fix this without causing it problems to the first case.

2 Answers

The problem is that trim does not modify the original String. As a consequence, when you calculate the substring you obtain different results depending on whether the input String has or not white spaces at the beginning or end, because indexOf is operating on the original String.

One possible solution could be the following:

// Trim the value
String trimmed = currLine.trim();
// And operate with it
String parameters = trimmed.substring(trimmed.indexOf("("),
                    trimmed.indexOf(")")-1);

A possible better approach would be to compute a regex over the provided value to extract the information between parenthesis, something like:

Matcher m = Pattern.compile("\\((.*?)\\)").matcher(currLine);
if (m.find()) {
  String parameters = m.group(1);
  // Operate with parameters
}

It should be as follows:

String parameters = currLine.substring(currLine.indexOf("(") + 1, currLine.indexOf(")")).trim();

Demo:

public class Main {
    public static void main(String[] args) {
        String currLine = "void                    foo                   (    int a      ,      String      b              )               {                 ";
        String parameters = currLine.substring(currLine.indexOf("(") + 1, currLine.indexOf(")")).trim();
        System.out.println(parameters);
    }
}

Output:

int a      ,      String      b

Note that String#substring(int beginIndex, int endIndex) returns the substring beginning at the specified beginIndex and extends to the character at index endIndex - 1.

Related