所以我试图提示用户在字符串中输入任何单词。然后我想提示他们计算他们想要计算的任何字母的出现次数。因此,如果他们在像#34这样的字符串中输入单词,那么这是一个测试"他们搜索" t"例如,字符串&#34中的返回值为3 t;这是一个测试"。我对这里的去处感到有点困惑......
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
String inputValue;
String s = "";
System.out.print("Enter a string of words or type done to exit: ");
inputValue = input.readLine();
System.out.print("Which letter would you like to count: ");
s = input.readLine();
int counter = 0;
我正在考虑做一个for循环并做一些像counter++
这样的事情。
答案 0 :(得分:1)
以上提供的答案是正确的,但我想使用不同的方法来计算字符串中字符的出现次数。
String string = "this is a testing string";
int count = string.length() - string.replaceAll("t", "").length();
或者
int counter = string.split("t").length - 1;
如果要检查$
等字符,则需要转义元字符。
答案 1 :(得分:0)
使用Apache commons-lang,您只需执行
int counter = StringUtils.countMatches(s, intputValue);
但如果您真的想要编码,那么您可以使用
public int count(String fullString, char valueToCount)
{
int count = 0;
for (int i=0; i < fullString.length(); i++)
{
if (fullString.charAt(i) == valueToCount)
count++;
}
return count;
}
另一个解决方案包括替换字符串中除输入字符之外的所有内容并返回修剪字符串的长度。
return s.replaceAll("[^" + inputValue + "]", "").length();