c++字符串分割( split string)
利用工厂模式的设计方法,为装饰者模式创建对象,写了个简单的字符串分割
#include <string> #include <iostream> #include <vector> using namespace std; void substring( string originString,vector<string> &splittedString ){ int begin = 0; size_t len = originString.length(); for(int i = 0;i<=len;i++){ if(originString[i] == ',') { splittedString.push_back(originString.substr(begin,i - begin)); begin = i+1 ; } } splittedString.push_back(originString.substr(begin, len - begin)); } int main(){ vector<string> splittedString;// = {string("hello"),string("hello"),string("hello")}; string originString = "apple,banana,orange"; substring(originString, splittedString); for( int i = 0;i<=2;i++) cout<<splittedString[i]<<'\n'; getchar(); return 0; };
想了想,觉得c语言用字符指针实现起来不会这么臃肿