用java利用string类的各种方法,分别判断字符是否为“?”、“!”、“.”,用3个计数器分别计数
时间: 2024-01-21 11:05:04 浏览: 23
字符串中 "?"、"!"、"." 的出现次数。
好的,我明白了。以下是代码示例:
```
public static void main(String[] args) {
String str = "Hello! How are you?";
int countQuestion = 0, countExclamation = 0, countPeriod = 0;
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
if (ch == '?') {
countQuestion++;
} else if (ch == '!') {
countExclamation++;
} else if (ch == '.') {
countPeriod++;
}
}
System.out.println("Question marks: " + countQuestion);
System.out.println("Exclamation marks: " + countExclamation);
System.out.println("Periods: " + countPeriod);
}
```
这个程序中,我们使用了String类的一个常用方法charAt()来逐个访问字符串中的字符,然后判断每个字符是否为"?"、"!"、"。",并累加计数器的值。最后,我们输出每个符号出现的次数。希望这个程序能为你解决问题。