利用String类的各种方法,分别判断字符是否为“?”、“!”、“.”,用3个计数器分别计数。
时间: 2023-11-18 10:02:25 浏览: 32
好的,我可以回答你的问题。
利用String类的方法判断字符是否为“?”、“!”、“.”的代码如下:
```java
String str = "Hello, World! How are you?";
int questionMarkCount = 0;
int exclamationMarkCount = 0;
int periodCount = 0;
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if (c == '?') {
questionMarkCount++;
} else if (c == '!') {
exclamationMarkCount++;
} else if (c == '.') {
periodCount++;
}
}
System.out.println("Question marks: " + questionMarkCount);
System.out.println("Exclamation marks: " + exclamationMarkCount);
System.out.println("Periods: " + periodCount);
```
这个代码会输出:
```
Question marks: 1
Exclamation marks: 1
Periods: 1
```
这里我们先定义了一个字符串 `str`,然后用三个计数器来计数字符串中每种符号的数量。
在循环中,我们使用了 `str.charAt(i)` 方法来获取字符串中第 `i` 个字符,并将其与“?”、“!”、“.”进行比较。如果匹配成功,则将对应的计数器加一。
最后我们输出三个计数器的值,就得到了字符串中各种符号的数量。
希望这个代码能对你有所帮助!