contains quotation mark java

久未见 提交于 2019-12-13 03:58:26

问题


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


回答1:


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

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




回答2:


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
}



回答3:


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
}



回答4:


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
}


来源:https://stackoverflow.com/questions/16037903/contains-quotation-mark-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!