查找 Java 字符串中出现的字符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3763970/
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
Find occurrences of characters in a Java String
提问by Steffan Harris
I would like to count the occurrences of a character in a string, suppose I have the string "aaaab", how would i count the amount of a's in it?
我想计算字符串中某个字符的出现次数,假设我有字符串“aaaab”,我如何计算其中 a 的数量?
采纳答案by jjnguy
The code looks way easier to read if you don't use regular expressions.
如果不使用正则表达式,代码看起来更容易阅读。
int count = 0;
for(int i =0; i < string.length(); i++)
if(string.charAt(i) == 'a')
count++;
count
now contains the number of 'a's in your string. And, this performs in optimal time.
count
现在包含字符串中“a”的数量。而且,这会在最佳时间执行。
Regular expressions are nice for pattern matching. But just a regular loop will get the job done here.
正则表达式非常适合模式匹配。但是只需一个常规循环就可以完成这里的工作。
回答by dty
A simple loop over the characters would do it.
一个简单的字符循环就可以了。
public int countChars(char c, String s) {
int result = 0;
for (int i = 0, n = s.length(); i < n; i++) {
if (s.charAt(i) == c) {
result++;
}
}
return result;
}
回答by Mike G
Try using Apache Commons' StringUtils:
尝试使用Apache Commons 的 StringUtils:
int count = StringUtils.countMatches("aaaab", "a");
// count = 4
回答by Aillyn
int count = 0;
for (char c : string.toCharArray())
if (c == 'a')
count++;
回答by dogbane
Guava's CharMatcherAPI is quite powerful and concise:
Guava 的CharMatcherAPI 非常强大和简洁:
CharMatcher.is('a').countIn("aaaab"); //returns 4
回答by tangens
Here is a really short solution without any extra libraries:
这是一个非常简短的解决方案,没有任何额外的库:
String input = "aaaab";
int i = -1, count = 0;
while( (i = input.indexOf( 'a', i + 1 ) ) != -1 ) count++;
System.out.println( count );
回答by Tony Ennis
Regular expressions aren't particularly good at counting simple things. Think ant+sledgehammer. They are good at busting complex strings up into pieces.
正则表达式并不是特别擅长计算简单的事情。想想蚂蚁+大锤。他们擅长将复杂的字符串分解成碎片。
Anyway, here's one solution the OP is interested in - using a regex to count 'a's:
无论如何,这是 OP 感兴趣的一种解决方案 - 使用正则表达式来计算“a”:
public class Reggie {
public static void main(String[] args) {
Pattern pattern = Pattern.compile("[^a]*a");
Matcher matcher = pattern.matcher("aaabbbaaabbabababaaabbbbba");
int count = 0;
while(matcher.find()) {
count++;
}
System.out.println(count+" matches");
}
}
This is a pretty slow way to do it, as pointed out by others. Worse, it isn't the easiest and certainly isn't the most likely to be bug-free. Be that as it may, if you wanted something a little more complex than 'a' then the regex would become more appropriate as the requested string got more complex. For example, if you wanted to pick dollar amounts out of a long string then a regex could be the best answer.
正如其他人所指出的那样,这是一种非常缓慢的方法。更糟糕的是,它不是最简单的,当然也不是最有可能没有错误的。尽管如此,如果您想要比 'a' 更复杂的东西,那么随着请求的字符串变得更复杂,正则表达式将变得更合适。例如,如果您想从一个长字符串中提取美元金额,那么正则表达式可能是最好的答案。
Now, about the regex: [^a]*a
现在,关于正则表达式: [^a]*a
This [^a]*
means 'match zero or more non-'a' characters. This allows us to devour non-'a' crud from the beginning of a string: If the input is 'bbba' then [^a]*
will match 'bbb'. It doesn't match the 'a'. Not to worry, the trailing 'a' in the regex says, "match exactly one 'a'". So our regex says, "match zero or more non-'a' characters that are followed by an 'a'."
这[^a]*
意味着“匹配零个或多个非“a”字符。这允许我们从字符串的开头吞噬非 'a' 的 crud:如果输入是 'bbba' 那么[^a]*
将匹配 'bbb'。它与“a”不匹配。不用担心,正则表达式中尾随的 'a' 表示“完全匹配一个 'a'”。所以我们的正则表达式说,“匹配零个或多个非 'a' 字符,后跟一个 'a'。”
Ok. Now you can read about Pattern and Matcher. The nutshell is that the Pattern is a compiled regular expression. It is expensive to compile a regex so I make mine static so they only get compiled once. The Matcher is a class that will apply a string to a Pattern to see if it matches. Matcher has state information that lets it crawl down a string applying a Pattern repeatedly.
好的。现在您可以阅读有关模式和匹配器的信息。简而言之,Pattern 是一个编译后的正则表达式。编译正则表达式的成本很高,所以我将我的正则表达式设为静态,这样它们只会被编译一次。Matcher 是一个将字符串应用于 Pattern 以查看它是否匹配的类。Matcher 具有状态信息,使其可以重复应用 Pattern 沿着字符串爬行。
The loop basically says, "matcher, crawl down the string finding me the next occurrence of the pattern. If we find it, increment the counter." Note the character sequences being found by Matcher isn't just 'a'. It is finding sequences like the following: 'a', 'bbba', 'bba', 'ba', etc. That is, strings that don't contain an 'a' except for their last character.
循环基本上是说,“匹配器,沿着字符串向下爬行,找到模式的下一次出现。如果我们找到它,就增加计数器。” 请注意,Matcher 找到的字符序列不仅仅是“a”。它正在查找如下序列:'a'、'bbba'、'bba'、'ba' 等。也就是说,除了最后一个字符外不包含 'a' 的字符串。
回答by jazzmann76
String string = "aaab";
int count = string.length() - string.replaceAll("a", "").length();
instead of "a" use a regex like "[a-zA-Z]" to count all word characters
而不是“a”,使用像“[a-zA-Z]”这样的正则表达式来计算所有单词字符
回答by Kuldeep Singh
You can simply use this:
你可以简单地使用这个:
String a = "i am here as junior java programmer";
Set temp = new HashSet();
char[] chararray=a.toCharArray();
Set temp=new HashSet();
for(int i=0;i<chararray.length;i++)
{
int count=0;
for (int j=0;j<chararray.length;j++) {
if (chararray[i]==chararray[j]) {
count++;
}
}
if (temp.add(chararray[i])!=false)
System.out.println("Character "+chararray[i]+" occur "+count);
}
回答by Manish Sahni
String searchFor = "a";
String base = "aaaab";
int count=0;
int index =base.indexOf(searchFor);
while(index!=-1){
++count;
index = base.indexOf(searchFor, index+searchFor.length());
}
System.out.println(count);