我们输入一个字符串,中间有英文字母和英文的逗号如“terry,is,good”。写一个C++程序对该字符串进行处理,利用栈实现单词的反向输出,各单词之间通过回车隔开。
时间: 2024-03-27 15:35:07 浏览: 24
好的,以下是一个C++程序,实现了对输入字符串的处理,利用栈实现单词的反向输出,各单词之间通过回车隔开:
```c++
#include <iostream>
#include <stack>
#include <sstream>
using namespace std;
string reverseString(string s) {
stack<string> stk;
stringstream ss(s);
string word, res;
while (getline(ss, word, ',')) {
stk.push(word);
}
while (!stk.empty()) {
res += stk.top() + "\n";
stk.pop();
}
return res;
}
int main() {
string s = "terry,is,good";
cout << reverseString(s) << endl;
return 0;
}
```
程序的主要思路与Python程序相似,首先将输入的字符串按照逗号进行分割,得到单词列表,然后将单词依次压入栈中。最后将栈中的单词依次弹出,拼接成字符串并加上回车符,最终得到反向输出的结果。
运行程序,输出结果为:
```
good
is
terry
```
相关问题
我们输入一个字符串,中间有英文字母和英文的逗号如“terry,is,good”。写一个程序对该字符串进行处理,利用栈实现单词的反向输出,各单词之间通过回车隔开。
好的,我来为您编写一个Python程序:
```python
def reverse_string(s):
stack = []
for word in s.split(','):
stack.append(word.strip())
res = ""
while stack:
res += stack.pop() + "\n"
return res.strip()
s = "terry,is,good"
print(reverse_string(s))
```
程序的主要思路是利用栈来实现单词的反向输出,首先将输入的字符串按照逗号进行分割,得到单词列表,然后将单词依次压入栈中。最后将栈中的单词依次弹出,拼接成字符串并加上回车符,最终得到反向输出的结果。
运行程序,输出结果为:
```
good
is
terry
```
写一段程序:输入一串字符,统计英文字母、空格、数字、和其他字符个数
以下是Python的程序实现:
```
string = input("请输入一串字符:")
# 初始化计数器
letter_count = 0
digit_count = 0
space_count = 0
other_count = 0
# 遍历字符串中的每个字符,判断它属于哪一类
for char in string:
if char.isalpha():
letter_count += 1
elif char.isdigit():
digit_count += 1
elif char.isspace():
space_count += 1
else:
other_count += 1
# 输出统计结果
print("英文字母数量:", letter_count)
print("数字数量:", digit_count)
print("空格数量:", space_count)
print("其他字符数量:", other_count)
```
程序先输入一串字符,然后利用 `for` 循环遍历每个字符,通过 `isalpha()`、`isdigit()`、`isspace()` 函数判断这个字符属于哪一类,并对应的计数器加一。最后输出各类字符的数量。