0

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   

2 Answers 2

3

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]
Sign up to request clarification or add additional context in comments.

Comments

1

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;
}

1 Comment

Works the same but i think using StringUtils.countMatches is neater, int indexAll[] = new int[StringUtils.countMatches(command,"\"")]; but that's just preference. commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.