將字串中開頭和結尾空格去掉,並且中間空格僅僅保留一個
阿新 • • 發佈:2019-02-13
<1>這樣其實只是覆蓋,並未完成任務,因為string不是以'\0'結尾的
#include<iostream> #include<string> using namespace std; ///////////////////////////////// void fun(string& s) //同p,也是字串中間空格僅僅保留一個,李重陽推薦 { int begin = 0; while(s[begin] == ' ') //去除開頭空格 begin++; int j=0; for(int i = begin;i < s.size()-1;i++) { if(s[i]==' '&&s[i+1]==' ') continue; s[j++]=s[i]; } s[j]='\0'; } ////////////////////////////////// void main() { string s = " wer e e "; cout<<s<<endl; fun(s); cout<<s<<endl; cout<<s.size()<<endl; } /* wer e e wer e e 11 */
<2>char*版本,才實現了任務
#include<iostream> #include<string> using namespace std; ///////////////////////////////// void fun(char* s) //同p,也是字串中間空格僅僅保留一個,李重陽推薦 { int begin = 0; while(s[begin] == ' ') //去除開頭空格 begin++; int j=0; for(int i = begin;i < strlen(s)-1;i++) { if(s[i]==' '&&s[i+1]==' ') continue; s[j++]=s[i]; } s[j]='\0'; } ////////////////////////////////// void main() { char s[] = " wer e e "; cout<<s<<endl; fun(s); cout<<s<<endl; cout<<strlen(s)<<endl; } /* wer e e wer e e 7 */