一個句子中也許有多個連續空格,過濾掉多餘的空格,只留下一個空格。ios
Hello world.This is c language.
Hello world.This is c language.
1 #include<stdio.h> 2 #include<string.h> 3 int main() 4 { 5 char a[500],i; 6 gets(a); 7 for(i=0;i<strlen(a);i++) 8 { 9 if(a[i]!=' '&&a[i]!='\0') printf("%c",a[i]); 10 else if(a[i]==' '&&a[i+1]!=' ') printf(" "); 11 } 12 return 0; 13 }
1 //提交時會有pe 2 #include <iostream> 3 #include <string> 4 using namespace std; 5 int main() 6 { 7 string s; 8 getline(cin, s); 9 int pos; 10 for (int i=0;i<s.length();++i) 11 { 12 if ((pos = s.find(" ")) != string::npos) 13 { 14 s.replace(pos, 2, " "); 15 } 16 } 17 cout << s; 18 return 0; 19 }
1 #include <iostream> 2 #include <string> 3 using namespace std; 4 int main() 5 { 6 string s; 7 getline(cin, s); 8 int pos; 9 for (int i=1;i<s.length();++i) 10 { 11 if (s[i]==' '&&s[i+1]==' ') 12 { 13 s.erase(i,1); 14 i--; 15 } 16 } 17 cout << s; 18 return 0; 19 }