用C++数组实现删除用户输入的字符串中的空白并输出,空白包括空格和Tab
时间: 2024-05-10 15:20:42 浏览: 21
```c
#include <stdio.h>
#include <string.h>
int main() {
char str[100];
printf("请输入字符串:");
fgets(str, 100, stdin); // 获取用户输入的字符串
int len = strlen(str); // 获取字符串长度
char new_str[len]; // 创建一个新的字符串数组,用于存储去除空白后的字符串
int j = 0; // 记录新字符串的下标
for (int i = 0; i < len; i++) {
if (str[i] != ' ' && str[i] != '\t') { // 如果不是空格或制表符
new_str[j] = str[i]; // 将该字符加入新字符串中
j++; // 新字符串下标加1
}
}
new_str[j] = '\0'; // 为新字符串添加结束符
printf("去除空白后的字符串为:%s", new_str); // 输出去除空白后的字符串
return 0;
}
```
相关问题
c++如何输入字符串
在C++中,有多种方法可以输入字符串。其中最常用的方法是使用getline()函数。这个函数可以接收一个字符串,包括空格与tab键。例如,可以使用以下代码输入一个字符串:
string str;
getline(cin, str);
另外,也可以使用cin.getline()函数来输入字符串,但是这个函数只能输入不包含空格的字符串。例如,可以使用以下代码输入一个不包含空格的字符串:
char str[100];
cin.getline(str, 100);
还可以使用cin>>运算符来输入字符串,但是这个方法只能输入不包含空格的字符串。例如,可以使用以下代码输入一个不包含空格的字符串:
char str[100];
cin>>str;
用C++代码写一个程序:求一个字符串中最长的连续出现的字符,输出该字符及其出现次数。字符串中无空白字符(空格、回车和tab),如果这样的字符不止一个,则输出出现最早的字符。
```c
#include <stdio.h>
#include <string.h>
int main()
{
char str[100];
scanf("%s", str);
int len = strlen(str);
char maxChar = str[0];
int maxCount = 1;
int count = 1;
for (int i = 1; i < len; i++) {
if (str[i] == str[i - 1]) {
count++;
} else {
if (count > maxCount) {
maxChar = str[i - 1];
maxCount = count;
}
count = 1;
}
}
if (count > maxCount) {
maxChar = str[len - 1];
maxCount = count;
}
printf("%c %d\n", maxChar, maxCount);
return 0;
}
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![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)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)