string 按照指定字符分割

int main()
{
    string line,b;
    getline(cin,line);
    stringstream ss(line);
    while(ss>>b) {
        cout<<b<<endl;
    }
    
}

string读取某一行,然后按空格分隔吹每一个string

char str[] = "now#the tiger is coming#please run away";
char delims[] = "#";
char *result = NULL;
 
result = strtok( str, delims );
 
while( result != NULL )
{
    printf( "result is "%s"
", result );
    result = strtok( NULL, delims );
}

字符分割

void split(string &str, string delimit, vector<string>&result) {
    size_t pos = str.find(delimit);
    str += delimit;//将分隔符加入到最后一个位置,方便分割最后一位
    while (pos != string::npos) {
        result.push_back(str.substr(0, pos));
        str = str.substr(pos + 1);//substr的第一个参数为起始位置,第二个参数为复制长度,默认为string::npos到最后一个位置
        pos = str.find(delimit);
    }
}
int main() {
    string str;
    string delimit;
    while (cin>>str)
    {
        cin >> delimit;
        vector<string> result;
        split(str, delimit, result);
        for (int i = 0; i < result.size(); ++i) {
            cout << result[i] << ' ';
        }
    }
}
原文地址:https://www.cnblogs.com/yuguangyuan/p/13357356.html