1 s += " "; //这里在最后一个字符位置加上空格,这样最后一个字符串就不会遗漏 2 string temp = ""; //临时字符串 3 vector<string> vec; //存放字符串的数组 4 for (char ch : s) //遍历字符句子 5 { 6 if (ch == ' ') //遇到空格 7 { 8 if (!tmp.empty()) //临时字符串非空 9 { 10 vec.push_back(tmp); 11 tmp.clear(); //清空临时字符串 12 } 13 } 14 else 15 tmp += ch; 16 }
1 s += " "; 2 string temp = ""; 3 vector<string> vec; 4 for (char ch : s) 5 { 6 if (ch == ' ') 7 { 8 vec.push_back(tmp); 9 tmp.clear(); 10 } 11 else 12 tmp += ch; 13 }
参考链接:https://leetcode-cn.com/problems/fan-zhuan-dan-ci-shun-xu-lcof/solution/yi-ge-mo-ban-shua-bian-suo-you-zi-fu-chu-x6vh/