如何用单个空格替换多个空格?

好吧,我正在寻找一个减少字符串中多个空格字符的函数。

例如,给出字符串s

 s="hello__________world____!" 

该函数必须返回"hello_world_!"

在python中我们可以通过regexp简单地完成它:

 re.sub("\s+", " ", s); 

修改字符串的版本,如果必须保留原始字符串,则在副本上运行它:

 void compress_spaces(char *str) { char *dst = str; for (; *str; ++str) { *dst++ = *str; if (isspace(*str)) { do ++str; while (isspace(*str)); --str; } } *dst = 0; } 

C标准库中没有这样的function。 必须编写一个函数来执行此操作或使用第三方库。

以下function应该可以解决问题。 使用源字符串作为目标指针来执行适当的操作。 否则,请确保目标缓冲区的大小足够大。

 void simplifyWhitespace(char * dst, const char * src) { for (; *src; ++dst, ++src) { *dst = *src; if (isspace(*src)) while (isspace(*(src + 1))) ++src; } *dst = '\0'; } 
 void remove_more_than_one_space(char *dest, char *src) { int i, y; assert(dest && src); for(i=0, y=0; src[i] != '\0'; i++, y++) { if(src[i] == ' ' && src[i+1] == ' ') { /* let's skip this copy and reduce the y index*/ y--; continue; } /* copy normally */ dest[y] = src[i]; } dest[y] = '\0'; } int main() { char src[] = "Hello World ! !! !"; char dest[strlen(src) + 1]; remove_more_than_one_space(dest, src); printf("%s\n", dest); } 

我刚刚做了这个,希望它有所帮助。

 #include #include #include int main() { char word[100]; gets(word); //the word has more than a single space in between the words int i=0,l,j; l=strlen(word); for (i=0;i 

这段代码非常简单,对我来说就像一个魅力。 我不知道这段代码是否会遇到其他一些我没有遇到过的问题,但是现在这个问题很有用。

我只是学习C,所以我使用了更基本的代码。 我正在阅读“C编程语言”的第一章,我试图在那里找到任务集的答案。

这就是我提出的:

 #include  int main() { /* Set two integers: c is the character being assessed, lastspace is 1 if the lastcharacter was a space*/ int c, lastspace; lastspace = 0; /* This while loop will exit if the character is EOF The first "If block" is true if the character is not a space, and just prints the character It also tells us that the lastcharacter was not a space The else block will run if the character is a space Then the second IF block will run if the last character was not also a space (and will print just one space) */ while((c = getchar()) != EOF){ if (c != ' '){ putchar(c); lastspace = 0; } else { if (lastspace != 1) putchar(c); lastspace = 1; } } return 0; } 

希望有所帮助! 另外,我很清楚这段代码可能没有优化,但对于像我这样的初学者来说它应该很简单!

谢谢,菲尔

这样做的另一种方法是只打印第一次出现的空格,直到下一个字符出现,这是我的暴力解决方案。

 #include typedef int bool; #define True 1 #define False 0 int main() { int t; bool flag = False; while ((t = getchar()) != EOF) if (t == ' ' && !flag) { putchar(' '); flag = True; // flag is true for the first occurence of space } else if(t == ' '&& flag) continue; else { putchar(t); flag = False; } return 0; } 

希望能帮助到你。