使用java语言编写,已知字符串“this is a test of java”,统计字符串中字母s出现的次数
时间: 2023-05-19 17:03:52 浏览: 90
这个问题很简单,使用Java的字符串函数可以很容易地解决。以下是代码示例:
```java
String str = "this is a test of java";
int count = 0;
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == 's') {
count++;
}
}
System.out.println("字母s出现的次数为:" + count);
```
输出结果为:
```
字母s出现的次数为:2
```
相关问题
使用java语言编写,已知字符串“this is a test of java”,取出字符串test
可以使用Java中的substring方法来取出字符串test,代码如下:
String str = "this is a test of java";
String test = str.substring(10, 14);
其中,10是test字符串在原字符串中的起始位置,14是test字符串在原字符串中的结束位置(不包括14)。
在已知字符串中统计各字母出现的次数
以下是两种在已知字符串中统计各字母出现次数的方法:
1. Python实现
```python
s = input().lower() # 将字符串转换为小写
count = [0] * 26 # 初始化计数器
for c in s:
if c.isalpha(): # 判断是否为字母
count[ord(c) - ord('a')] += 1 # 统计字母出现次数
for i in range(26):
if count[i] > 0:
print(chr(i + ord('A')), count[i]) # 输出字母和出现次数
```
2. C++实现
```c++
#include <iostream>
#include <cstring>
using namespace std;
int main() {
string s;
cin >> s;
int flag[26] = {0};
for (int i = 0; i < s.length(); i++) {
if (s[i] >= 'a' && s[i] <= 'z') {
s[i] = s[i] - 32; // 将小写字母转换为大写字母
}
if (s[i] >= 'A' && s[i] <= 'Z') {
flag[s[i] - 65]++; // 统计字母出现次数
}
}
for (int i = 0; i < 26; i++) {
if (flag[i] > 0) {
cout << (char)(i + 65) << " " << flag[i] << endl; // 输出字母和出现次数
}
}
return 0;
}
```