今天写了个小编程,去除字符串中多余的空格,例如"I___am_____a______student."(下划线表示空格哈,打多个空格显示的还是一个),最后输出”I am a student.”
现在把自己的思路贴上,欢迎大家留言指正。
思路就是定义两个指针next和tail,一个在前面寻找非空格的字符,另外一个在后面一步一步移动,把后面的字符全部转移到前面来;然后为了去除多余的空格,也就是有多个或者一个空格的地方要留一个空格。
#include <iostream>
using namespace std;
char * deleteSpace(char * str){
char * tail = str;
char * next = str;
while(*next){ // 两个if可以合并到一块儿,这样写只是为了看着方便
if(*next != ' '){ // 查找不是空格的字符
*tail = *next;
tail++;
}
if(*next == ' ' && *(next-1) != ' '){ // 只留一个空格的判断条件;当前字符为空格且前一个不为空格。
*tail = *next;
tail++;
}
next++;
}
*tail='\0'; // 字符串结束
return str;
}
int main(){
char str[] = "i am a student.";
char *res = deleteSpace(str);
cout << res << endl;
return 0;
}
---------------------
作者:yooliee
来源:优快云
原文:https://blog.youkuaiyun.com/yooliee/article/details/77953578?utm_source=copy
版权声明:本文为博主原创文章,转载请附上博文链接!
整体思路:将后续字符往前移动。
源代码:
char s1[] ="NI h a o zho ng qiu";
int n=strlen(s1);
printf("strlen(s1)=%d\n",n);
int i=0;
int space = 0;
int j=0;
for(i=0;i<n;i++){
//判断当前字符是否是空格
if(isspace(s1[i+space])){
space+=1;
j=(i+space);
//判断当前字符后续是否有连续空格
while(s1[j]==' '){
j++;
space+=1;
}
}
//将后续字符往前挪动
s1[i] = s1[i+space];
}
printf("%s\n",s1);
---------------------
作者:sjunothing
来源:优快云
原文:https://blog.youkuaiyun.com/sjunothing/article/details/78740256?utm_source=copy
版权声明:本文为博主原创文章,转载请附上博文链接!