AnchovyLegend
AnchovyLegend

Reputation: 12538

Java: Using String.indexOf() to check for the apostrophe character

I am trying to parse a string and I need to use substring to do it. The string contains the apostrophe characters. My question is, how do I use temp to get String.indexOf to get the index of the apostrophe character?

//temp variable currently contains the string 'hello' including the apostrophe character
String finalWord = temp.substring(temp.indexOf('''), temp.indexOf('.')); 

Upvotes: 1

Views: 5878

Answers (2)

Bohemian
Bohemian

Reputation: 425208

Based on your last comment, which declares what you're actually trying to do...

There is a simple one-line solution for extracting every apostrophe-quoted string from input:

String[] quotedStrings = input.replaceAll("^.*?'|'[^']*$", "").split("'.*?('|$)");

Here's some test code:

public static void main(String[] args) {
    String input = "xxx'foo'xxx'bar'xxx'baz'xxx";
    String[] quotedStrings = input.replaceAll("^.*?'|'[^']*$", "").split("'.*?('|$)");
    System.out.println(Arrays.toString(quotedStrings));
}

Output:

[foo, bar, baz]

Upvotes: 0

Juvanis
Juvanis

Reputation: 25950

Your variable name is wrong(final is a reserved word) and you should use escape character:

String finalword = temp.substring(temp.indexOf('\''), temp.indexOf('.')); 

Upvotes: 10

Related Questions