Check if string is a punctuation character

北慕城南 提交于 2019-11-26 17:14:44

问题


Let's say I have a String array that contains some letters and punctuation

String letter[] = {"a","b","c",".","a"};

In letter[3] we have "."

How can I check if a string is a punctuation character? We know that there are many possible punctuation characters (,.?! etc.)

My progress so far:

for (int a = 0; a < letter.length; a++) {
    if (letter[a].equals(".")) { //===>> i'm confused in this line
        System.out.println ("it's punctuation");
    } else {
        System.out.println ("just letter");
    }
}

回答1:


Do you want to check more punctuations other than just .?

If so you can do this.

String punctuations = ".,:;";//add all the punctuation marks you want.
...
if(punctuations.contains(letter[a]))



回答2:


Here is one way to do it with regular expressions:

if (Pattern.matches("\\p{Punct}", str)) {
    ...
}

The \p{Punct} regular expression is a POSIX pattern representing a single punctuation character.




回答3:


Depending on your needs, you could use either

Pattern.matches("\\p{Punct}", str)

or

Pattern.matches("\\p{IsPunctuation}", str)

The first pattern matches the following 32 characters: !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~

The second pattern matches a whopping 632 unicode characters, including, for example: «, », ¿, ¡, §, , , , , , and .

Interestingly, not all of the 32 characters matched by the first pattern are matched by the second. The second pattern does not match the following 9 characters: $, +, <, =, >, ^, `, |, and ~ (which the first pattern does match).

If you want to match for any character from either character set, you could do:

Pattern.matches("[\\p{Punct}\\p{IsPunctuation}]", str)



回答4:


Try this method: Character.isLetter(). It returns true if the character is a letter (a-z, uppercase or lowercase), returns false if character is numeric or symbol.

e.g. boolean answer = Character.isLetter('!');

answer will be equal to false.




回答5:


import String ... if(string.punctuation.contains(letter[a]))




回答6:


function has_punctuation(str) {

  var p_found = false;
  var punctuations = '`~!@#$%^&*()_+{}|:"<>?-=[]\;\'.\/,';
  $.each(punctuations.split(''), function(i, p) {
    if (str.indexOf(p) != -1) p_found = true;
  });

  return p_found;

}


来源:https://stackoverflow.com/questions/13925454/check-if-string-is-a-punctuation-character

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