Channa
Channa

Reputation: 5233

Java String get multiple index values

Rather than using "split" method, is there any easy way to get all the index values of double quote character ("") on following String. Thanks.

String command = "-u User -P Password mkdir \"temp dir\" rmdir \"host dir\"";
int[] indexAll = command.indexOf ("\""); // This line of code is not compile, only I expect this kind of expression   

Upvotes: 0

Views: 4137

Answers (2)

JRoc
JRoc

Reputation: 21

This is similar to Sotirios method, but you can avoid converting back to array, by first finding number of occurrences so that you can initialize array.

String command = "-u User -P Password mkdir \"temp dir\" rmdir \"host dir\"";
int count = command.length() - command.replace("\"", "").length();
int indexAll[] = new int[count];
int position = 0;
for(int i = 0; i < count; i++) {
  position = command.indexOf("\"", position + 1);
  indexAll[i] = position;
}

Upvotes: 1

Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 279970

There is no built in method that does this.

Use the overloaded String#indexOf(String, int) method that accepts a starting position. Keep looping until you get -1, always providing the result of the previous call as the starting position. You can add each result in a List and convert that to an int[] later.

Alternatively, use Pattern and Matcher, looping while Matcher#find() returns a result.

Here are a few examples:

public static void main(String[] args) {
    String command = "-u User -P Password mkdir \"temp dir\" rmdir \"host dir\"";
    List<Integer> positions = new LinkedList<>();
    int position = command.indexOf("\"", 0);

    while (position != -1) {
        positions.add(position);
        position = command.indexOf("\"", position + 1);
    }
    System.out.println(positions);

    Pattern pattern = Pattern.compile("\"");
    Matcher matcher = pattern.matcher(command);
    positions = new LinkedList<>();

    while (matcher.find()) {
        positions.add(matcher.start());
    }

    System.out.println(positions);
}

prints

[26, 35, 43, 52]
[26, 35, 43, 52]

Upvotes: 3

Related Questions