用户输入一个字符串 s(长度<1000,以回车结束),请将所有句子首字母大写、过滤多余空格后输出, 即遇到多于1个的连续空格,仅保留一个空格。
时间: 2024-05-25 21:16:42 浏览: 11
s = input().strip() # 去除字符串两端的空格
result = ""
flag = True # 标记是否是句子的开头
for i in range(len(s)):
if s[i] == " ":
if flag: # 连续空格中的第一个空格
result += " "
flag = False
elif s[i] == "." or s[i] == "!" or s[i] == "?": # 句子的结尾
result += s[i]
flag = True
else:
if flag: # 句子的开头
result += s[i].upper()
flag = False
else:
result += s[i].lower()
print(result)
相关问题
运用C++编辑一个用户输入一个字符串 s(长度<1000,以回车结束),请将所有句子首字母大写、过滤多余空格后输出, 即遇到多于1个的连续空格,仅保留一个空格。
以下是使用C语言编写的代码,可以实现将用户输入的字符串s中的所有句子首字母大写、过滤多余空格后输出:
```
#include <stdio.h>
#include <ctype.h>
int main() {
char s[1000];
fgets(s, 1000, stdin); // 读入用户输入的字符串s
int i = 0;
while (s[i] != '\0') {
// 将句子的首字母转换为大写
if (i == 0 || s[i-1] == '.' || s[i-1] == '?' || s[i-1] == '!') {
s[i] = toupper(s[i]);
}
// 过滤多余空格
if (s[i] == ' ') {
int j = i + 1;
while (s[j] == ' ') {
j++;
}
if (j > i + 1) {
s[i] = ' ';
s[i+1] = s[j];
}
}
i++;
}
printf("%s", s); // 输出处理后的字符串s
return 0;
}
```
如果用户输入的字符串s为:"hello world. how are you? i am fine. thank you! "
则程序输出的结果为:"Hello world. How are you? I am fine. Thank you!"
用C语言用户输入一个字符串 s(长度<1000,以回车结束),请将所有句子首字母大写、过滤多余空格后输出, 即遇到多于1个的连续空格,仅保留一个空格。 例如 s = "what's your name? my name is Tony." 应输出:What's your name? My name is tony
以下是C语言代码实现:
#include <stdio.h>
#include <ctype.h>
int main() {
char s[1000];
fgets(s, 1000, stdin); // 读入字符串
int i = 0;
int flag = 0; // 标记是否为句子的开头
while (s[i] != '\0') {
if (isspace(s[i])) { // 如果是空格
if (flag) { // 如果前面是句子的开头
putchar(' '); // 输出一个空格
flag = 0; // 标记为不是句子的开头
}
} else {
if (flag == 0) { // 如果前面不是句子的开头
putchar(toupper(s[i])); // 输出大写字母
flag = 1; // 标记为句子的开头
} else {
putchar(tolower(s[i])); // 输出小写字母
}
}
i++;
}
return 0;
}
输入示例:
what's your name? my name is Tony.
输出示例:
What's your name? My name is tony.
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)