编写一个程序,清除用户输入字符串中的空格符并将之输出。(例如用户输入”a b”,输出”ab”)
时间: 2024-04-10 17:28:05 浏览: 20
可以使用一个循环遍历用户输入的字符串,然后判断每个字符是否为空格符,并将非空格符的字符拼接到一个新的字符串中。以下是一个示例代码:
```c++
#include <iostream>
#include <string>
using namespace std;
string removeSpaces(string input) {
string output = "";
for (int i = 0; i < input.length(); i++) {
if (input[i] != ' ') {
output += input[i];
}
}
return output;
}
int main() {
string input;
cout << "请输入一个字符串: ";
getline(cin, input);
string result = removeSpaces(input);
cout << "去除空格后的字符串为: " << result << endl;
return 0;
}
```
运行结果:
```
请输入一个字符串: a b
去除空格后的字符串为: ab
```
相关问题
``` /*编写一个程序,清除用户输入字符串中空格符并将之输出 (例如用户输入“a b”,输出“ab”) ```
```python
def remove_spaces(string):
return string.replace(" ", "")
user_input = input("请输入字符串:")
result = remove_spaces(user_input)
print(result)
```
编写程序,输入一个字符串,再输入一个字符,在字符串中删除输入的字符,形成新的字符串并输出,程序保存为2.c
以下是2.c的代码实现:
```c
#include <stdio.h>
#include <string.h>
int main() {
char str[100], c;
int i, j;
printf("请输入一个字符串:");
scanf("%s", str);
printf("请输入一个字符:");
scanf(" %c", &c);
for(i = 0, j = 0; i < strlen(str); i++) {
if(str[i] != c) {
str[j] = str[i];
j++;
}
}
str[j] = '\0';
printf("删除后的字符串为:%s\n", str);
return 0;
}
```
程序的大致思路是:先输入一个字符串和一个字符,然后通过循环遍历字符串中的每一个字符,如果该字符与输入的字符不同,则将其保存到新的字符串中;否则跳过该字符。最终输出删除指定字符后的新字符串。
需要注意的是,为了避免输入字符时受到上一次输入的影响,第二个scanf前面需要加一个空格,这样可以清除输入缓冲区中的换行符。同时,在新字符串的结尾需要添加一个空字符'\0'来标志字符串的结束。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://img-home.csdnimg.cn/images/20210720083646.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)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)