简体   繁体   English

如何检查String是否包含多次相同的字母?

[英]How do I check if a String contains the same letter more than once?

I'm a bit confused in how I would check if a String contains the same letter more than once. 我对如何检查String是否包含多次相同的字母感到困惑。

ArrayList<String> words = new ArrayList<String>();

words.add("zebra");
words.add("buzzer");
words.add("zappaz");

Let's say I only want to print out any words which contain more than one "z", therefore only "buzzer" and "zappaz" would get printed. 假设我只想打印出包含多个“z”的任何单词,因此只会打印“蜂鸣器”和“zappaz”。 How would I do this? 我该怎么做?

要测试字符串是否包含两个z,您可以执行以下操作:

 boolean ok = word.matches(".*z.*z.*")

indexOf returns the... index of... a character in a string. indexOf返回...索引...字符串中的字符。 It also takes an optional argument specifying where to search. 它还需要一个可选参数来指定搜索位置。 If there is no match, it returns -1 . 如果没有匹配,则返回-1 So just use it twice: 所以只需使用它两次:

s.indexOf(letter, s.indexOf(letter) + 1) > -1

It works! 有用!

(For efficiency's sake, though, may as well check the first result .) (但是为了效率,也可以检查第一个结果 。)

A smart solution could be, removing the character you want to search and compare the length of the resulting string with the complete string. 一个聪明的解决方案可能是,删除您要搜索的字符,并将结果字符串的长度与完整的字符串进行比较。

ArrayList<String> words = new ArrayList<String>();

words.add("zebra");
words.add("buzzer");
words.add("zappaz");

for (String word : words) {
  // calculate the length difference
  if (word.length() - word.replace("z", "").length() > 1) {
    System.out.println(word);
  }
}

will print: 将打印:

buzzer
zappaz

Not very efficient, but it works and is pretty simple. 不是很有效,但它的工作原理非常简单。

public static void main(String[] args) {

  String s = "bazzer";
  String news = s.replaceAll("z", "");

    if(news.length() < s.length() -1 ){
        System.out.println(s);
    }

  }

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

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