How to filter out extra spaces in the C language?
In C language, the following methods can be used to filter out extra spaces:
- Traverse the string using pointers and save the filtered results in a new string.
#include <stdio.h>
#include <ctype.h>
#include <string.h>
void filterSpaces(char *str) {
char *filtered = str; // 用于保存过滤后的字符串
int isSpace = 0; // 标记当前字符是否为空格
// 遍历字符串
while (*str) {
if (isspace(*str)) {
// 如果当前字符为空格
if (!isSpace) {
// 如果前一个字符不是空格,则将当前字符保存到filtered中
*filtered++ = *str;
isSpace = 1; // 设置isSpace为1,表示当前字符为空格
}
} else {
// 如果当前字符不是空格,则将当前字符保存到filtered中
*filtered++ = *str;
isSpace = 0; // 设置isSpace为0,表示当前字符不是空格
}
str++;
}
// 在filtered的末尾添加字符串结束符'\0'
*filtered = '\0';
}
int main() {
char str[100];
printf("请输入字符串:");
scanf("%[^\n]", str);
filterSpaces(str);
printf("过滤后的字符串为:%s\n", str);
return 0;
}
- By using two pointers, one pointing to the original string and one to the filtered string, skip characters that do not meet the requirements.
#include <stdio.h>
#include <ctype.h>
#include <string.h>
void filterSpaces(char *str) {
char *filtered = str; // 用于保存过滤后的字符串
// 遍历字符串
while (*str) {
if (!isspace(*str)) {
// 如果当前字符不是空格,则将当前字符保存到filtered中
*filtered++ = *str;
}
str++;
}
// 在filtered的末尾添加字符串结束符'\0'
*filtered = '\0';
}
int main() {
char str[100];
printf("请输入字符串:");
scanf("%[^\n]", str);
filterSpaces(str);
printf("过滤后的字符串为:%s\n", str);
return 0;
}
Both of these methods can filter out extra spaces, with the output being the filtered string.