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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14092682/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 15:02:11  来源:igfitidea点击:

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

javastring

提问by rednaxela

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. How would I do this?

假设我只想打印包含多个“z”的任何单词,因此只会打印“蜂鸣器”和“zappaz”。我该怎么做?

回答by Denys Séguret

To test if a string contains two z, you can do this :

要测试字符串是否包含两个 z,您可以这样做:

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

回答by Ry-

indexOfreturns the... index of... a character in a string. It also takes an optional argument specifying where to search. If there is no match, it returns -1. So just use it twice:

indexOf返回... 字符串中字符的... 索引。它还需要一个可选参数来指定搜索位置。如果没有匹配项,则返回-1。所以只需使用它两次:

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

It works!

有用!

(For efficiency's sake, though, may as well check the first result.)

(不过,为了效率,不妨检查第一个结果。)

回答by Thomas Jungblut

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.

不是很有效,但它有效并且非常简单。

回答by someone

public static void main(String[] args) {

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

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

  }