0

how to I add an argument to check if a string contains ONE quotation mark ? I tried to escape the character but it doesn't work

words[i].contains()

EDIT: my bad, got some unclosed brackets, works fine now

Dodi
  • 2,201
  • 4
  • 30
  • 39

4 Answers4

5
words[i].matches("[^\"]*\"[^\"]*")

That is: any non-quotes, a quote, any non-quotes.

Joop Eggen
  • 107,315
  • 7
  • 83
  • 138
4

You could use something like this:

words[i].split("\"").length - 1

That would give you the amount of "s in your string. Therefore, just use:

if (words[i].split("\"").length == 2) {
    //do stuff
}
tckmn
  • 57,719
  • 27
  • 114
  • 156
2

You can check if the first quotation mark exists, and then check if the second one doesn't. It's much faster than using matches or split.

int index = words[i].indexOf('\"');
if (index != -1 && words[i].indexOf('\"', index + 1) == -1){
    // do stuff
}
johnchen902
  • 9,531
  • 1
  • 27
  • 69
  • "much faster?" yeah... about a ten nanosecond gain off 30 nanoseconds or something. You won't ever notice the difference – tckmn Apr 16 '13 at 16:04
0

To check number or quotes you can also use length of string after removing ".

int quotesNumber = words[i].length() - words[i].replace("\"", "").length();
if (quotesNumber == 1){
    //do stuff
}
Pshemo
  • 122,468
  • 25
  • 185
  • 269