从string中解析出单词
写了两个函数,分别借助不同的函数实现,代码的逻辑很简单:
#include <iostream> #include <string> #include <cstring> //strtok #include<vector> #include <cstdlib> using namespace std; //实现将一个字符串按照分隔符划分成单词 /* *思路: *每一个单词的开头也就是第一个非空格的位置,用start = find_first_not_of(' ', end)来得到 *每一个单词的结尾就是从start开始的第一个空格的前一个位置用end = find_first(' ', start)来得到 */ vector<string> split(const string& srcStr, const char sp) { vector<string> ret; if (srcStr.empty()) return ret; int start = 0; int end = 0; while( string::npos != (start = srcStr.find_first_not_of(sp, end)) ) { if (string::npos == (end = srcStr.find_first_of(sp, start))) end = srcStr.length(); ret.push_back(srcStr.substr(start, (end - start))) ; } return ret ; } /* *思路: *使用char * strtok ( char * str, const char * delimiters )函数,每次从srcStr中得到一个token *然后转化成string类型,存放到结果中 */ vector<string> split(char *srcStr, char *delimiters) { vector<string> ret; if (srcStr == NULL || delimiters == NULL) return ret; char *nextStr = NULL ; char *tmp = strtok_s(srcStr, delimiters, &nextStr) ; while( tmp ) { ret.push_back(string(tmp)) ; tmp = strtok_s(NULL, delimiters, &nextStr) ; } return ret ; } int main(int argc, char** argv) { string strNum; getline(cin, strNum) ; while( !strNum.empty() ) { cout << "输入的内容是:" << strNum << endl; vector<string> result = split(strNum, ' ') ; cout << "split1 划分出来的单词是:" << endl; for (size_t i = 0; i < result.size() ; ++ i) cout << "\"" << result[i] << "\" " ; cout << endl; result.clear() ; char *str = new char[strNum.length() + 1] ; memcpy(str, strNum.c_str(), strNum.length()) ; str[strNum.length()] ='\0' ; result = split(str, " ") ; cout << "split2 划分出来的单词是:" << endl; for (size_t i = 0; i < result.size(); ++ i) cout << "\"" << result[i] << "\" " ; cout << endl; delete[] str; getline(cin, strNum) ; } return 0 ; }