简体   繁体   English

计算字符的所有出现(字符串末尾除外)

[英]Count all occurrences of a character except at the end of the string

For example 例如

String text = "sentence";     // (number of e's = 2)

There are three e's in that string, but the result should be 2 because the third one is at the very end. 该字符串中有三个e,但结果应为2因为第三个在最后。 This is what I have so far: 这是我到目前为止的内容:

public static void main(String[] args) {
    int count =0;
    String text    = "sentence";
    Pattern pat = Pattern.compile("[e]+");
    Matcher m = pat.matcher(text);
    while (m.find()) {
        count++;
    }
    System.out.println(count);
}

Replace + which exists after e with negative lookahead. 用负前瞻替换e后面的+ e+ matches one or more e 's , so regex engine should consider eee as single match. e+匹配一个或多个e ,因此正则表达式引擎应将eee视为单个匹配项。 And a negative lookahead after e , ie e(?!$) helps to find all the e 's but not the one which exists at the end of a line. e后面进行负前瞻,即e(?!$)有助于找到所有e ,而不是找到存在于行尾的那个。

int count = 0;
String text = "sentence";
Pattern pat = Pattern.compile("e(?!$)");
Matcher m = pat.matcher(text);
while (m.find()) {
        count++;
}
System.out.println(count);

Matcher methods can tell you the start and end index of the match. Matcher方法可以告诉您Matcher的开始和结束索引。 If end (next character after) matches the length of the string then it's the last character. 如果end(后面的下一个字符)与字符串的长度匹配,则为最后一个字符。 Eg 例如

int count =0;
String text = "sentence";
Pattern pat = Pattern.compile("e");
Matcher m = pat.matcher(text);
while (m.find() && m.end() != text.length()) {
    count++;
}
System.out.println(count);

If you would like to exclude from counting last letter of a word instead of last word of the sentence, you can check whether the end character is alpha : 如果要排除单词的最后一个字母而不是句子的最后一个单词,可以检查结束字符是否为alpha:

int count =0;
String text = "sentence";
Pattern pat = Pattern.compile("e");
Matcher m = pat.matcher(text);
while (m.find() &&
       m.end() != text.length() &&
       Character.isAlphabetic(text.charAt(m.end()))) {
    count++;
}
System.out.println(count);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM