如何计算字符串中的特定字母?到目前为止这是我的代码:
公共类Main {
public static void main(String args[]) {
Scanner sc = new Scanner (System.in);
System.out.println("Type in a word: ");
String str1 = sc.nextLine();
System.out.println("Type in a letter in the word you want to look for");
String str2 = sc.nextLine();
int count = 0;
for(char c : str1.toCharArray()) {
if(c == 0) {
count++;
}
}System.out.println("There are " + count + " " + str2 + " in the word " + str1);
}
它显示为:输入一个单词:hello
在您要查找的单词中键入一个字母:l
单词hello中有0 l
我的代码出了什么问题?
将字符串转换为char数组并迭代它以找出给定char的出现次数。
int count = 0;
for (char d : str1.toCharArray()){
if(d == c)
count++;
}
您还可以使用正则表达式查找计数。但是你不能使用nextLine().charAt(0)
,你必须使用next()
。
String c = sc1.next();
int count = 0;
Pattern pattern = Pattern.compile(c);
Matcher matcher = pattern.matcher(str1);
while (matcher.find())
count++;
最后把它打印出来。
System.out.println("There are " + count + " " + c + " in the word " + str1);
这是方法:当char匹配时,你可以遍历charArray并增加计数器。
public static void main(String args[]) {
String number = "hello";
int count = 0;
for(char ch : number.toCharArray()) {
if(ch == 'l') {
count++;
}
}
System.out.println(count);
}