去掉字串中的多餘空格
阿新 • • 發佈:2018-11-17
#include <iostream> #include <string> using namespace std; string reverse(string s) { string res = ""; string::size_type start = 0; string::size_type end = 0; int sflag = 0; int eflag = 0; for (int i = 0; i < s.size(); i++) { if (s[i] == ' ' && i + 1 < s.size() && isalnum(s[i + 1])) { start = i + 1; sflag = 1; } if (isalnum(s[i]) && i + 1 < s.size() && s[i + 1] == ' ') { end = i; eflag = 1; } if (sflag && eflag) { string tmp = s.substr(start, end - start + 1); //cout << tmp << endl; res = res + tmp + " "; sflag = 0; eflag = 0; } } if (sflag == 1 && eflag == 0) { res += s.substr(start, s.size() - start); } cout << res << endl; return res; } int main() { string s = " mk am a student "; string res = reverse(s); string t = "mk am a"; cout << t << endl; system("pause"); return 0; }