c++ string 切割字符串, 按空格分割

//将字符串按空格分割
#include<bits/stdc++.h>
using namespace std;
int main(){
    string str;
    // getline(std::cin, str);
    str = " 123    abcd  789 0";
    vector<string> lis;
    string::iterator myBegin = str.begin();
    string::iterator myEnd = str.begin();
 
    //按空格分割
    while(1){
        myEnd = find(myBegin, str.end(), ' ');
        if(myBegin >= str.end()){ //退出条件
            break;
        }
        if(myEnd != myBegin)  //若要忽略多余的空格就加上这行:非空格时才存
            lis.push_back(string(myBegin, myEnd));
        myBegin = myEnd+1;
    }
    //按空格分割
    
    for(int i = 0; i < lis.size(); i++){
        cout<<lis[i]<<endl;
    }
    return 0;
}思路:while循环,循环内find找指定的字符,找到后就存入vector

猜你喜欢

转载自blog.csdn.net/m0_73313013/article/details/137829623
今日推荐