pta8-01 查找指定字符
时间: 2023-12-04 08:04:27 浏览: 61
题目描述:
编写一个程序,输入一个字符串和一个字符,统计该字符在字符串中出现的次数。
输入格式:
输入在一行中给出一个字符串和一个字符,中间隔着一个空格。
输出格式:
在一行中输出字符在字符串中出现的次数。
输入样例:
Hello World ! o
输出样例:
2
解题思路:
遍历字符串,判断每个字符是否等于给定字符,若相等则计数器加1。
参考代码:
```cpp
#include <iostream>
using namespace std;
int main()
{
string s;
char c;
getline(cin, s);
cin >> c;
int ans = 0;
for (int i = 0; i < s.length(); i++)
if (s[i] == c)
ans++;
cout << ans << endl;
return 0;
}
```
相关问题
pta7-2查找书籍
以下是一个解决pta7-2查找书籍问题的Python程序:
```python
n = int(input()) # 输入书籍数量
books = [] # 存储书籍信息的列表
# 循环读取书籍信息
for i in range(n):
book_info = input().split() # 输入格式为“价格 书名”,使用split()函数将其拆分为列表
book_info[0] = float(book_info[0]) # 将价格转换为浮点数
books.append(book_info) # 将书籍信息添加到列表中
# 使用max()和min()函数找到价格最高和最低的书籍
max_book = max(books, key=lambda x: x[0]) # 根据价格进行比较
min_book = min(books, key=lambda x: x[0])
# 输出结果
print("{:.2f}, {}".format(max_book[0], max_book[1]))
print("{:.2f}, {}".format(min_book[0], min_book[1]))
```
c语言pta7-1删除数字字符
以下是C语言实现删除数字字符的代码:
```c
#include <stdio.h>
#include <string.h>
int main()
{
char str[10000];
char new_str[10000];
int i, j = 0;
gets(str);
for (i = 0; i < strlen(str); i++) {
if (str[i] < '0' || str[i] > '9') {
new_str[j] = str[i];
j++;
}
}
new_str[j] = '\0';
printf("%s", new_str);
return 0;
}
```
该代码通过遍历输入的字符串,将非数字字符存入新的字符串中,最后输出新的字符串即可实现删除数字字符的功能。