我有这个字符串
"go for goa"
输出结果应该是
"go for goa"
我希望去除额外的空格。也就是说,两个或者更多连续的空格应该被替换成一个空格。我想使用一个原地算法来完成这个任务。
以下是我尝试过的代码,但它并没有起作用:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* Function to remove spaces in an string array */
char *removeSpaces(char *str) {
int ip_ind = 1;
/* In place removal of duplicate spaces*/
while(*(str + ip_ind)) {
if ((*(str + ip_ind) == *(str + ip_ind - 1)) && (*(str + ip_ind)==' ')) {
*(str_ip_ind-1)= *(str + ip_ind);
}
ip_ind++;
}
/* After above step add end of string*/
*(str + ip_ind) = '\0';
return str;
}
/* Driver program to test removeSpaces */
int main() {
char str[] = "go for go";
printf("%s", removeSpaces(str));
getchar();
return 0;
}