1

所以在python中你可以像这样分割字符串:

string = "Hello world!"
str1 , str2 = string.split(" ") 
print(str1);print(str2)

它打印:

Hello 
world!

我如何在 C++ 中做同样的事情?这没有用使用字符串分隔符(标准 C++)在 C++ 中解析(拆分)字符串,我需要将它们拆分,以便我可以像 print just str1 一样单独访问它们。

4

4 回答 4

6

如果您的分词器始终是一个空格 ( " ") 并且您可能不会使用其他字符 (例如s.split(',')) 对字符串进行分词,您可以使用字符串流:

#include <iostream>
#include <string>
#include <stringstream>

int main() {
    std::string my_string = " Hello   world!  ";
    std::string str1, str2;
    std::stringstream s(my_string);

    s>>str1>>str2;

    std::cout<<str1<<std::endl;
    std::cout<<str2<<std::endl;
    return 0;
}

请记住,此代码仅建议用于空白标记,如果您有许多标记,则可能无法扩展。输出:

Hello
World!
于 2021-07-15T15:56:36.807 回答
1
#include<bits/stdc++.h>
using namespace std;
int main(){
    string str ="123/43+2342/23432";
    size_t found = str.find("+");
    int b=found;
    int a,c;
    size_t found1 = str.find("/");
    if(found1!=string::npos){
        a = found1;
    }
    found1 = str.find("/",found1+1);
    if(found1!=string::npos){
        c = found1;
    }
    string tmp1 = str.substr(0,a-0);
    int num1 = stoi(tmp1);
    tmp1 = str.substr(a+1,b-a-1);
    int del1 = stoi(tmp1);
    tmp1 = str.substr(b+1,c-b-1);
    int num2 = stoi(tmp1);
    tmp1 = str.substr(c+1);
    int del2 = stoi(tmp1);

    cout<<num1<<" "<<del1<<" "<<num2<<" "<<del2<<endl;
    
    return 0;
}

当您找到 "/" 或 "+" 时,拆分字符串中给出的所有数字。

于 2021-08-18T21:00:19.990 回答
1

使用提升:

#include <iostream>
#include <boost/algorithm/string.hpp>
#include <vector>

int main()
{
    std::string line;
    while(std::getline(std::cin, line)) {
        std::vector<std::string> v;
        boost::split(v, line, boost::is_any_of(" "));
        for (const auto& s : v) {
            std::cout << s << " - ";
        }
        std::cout << '\n';
    }
    return 0;
}

https://godbolt.org/z/EE3xTavMr

于 2021-07-15T16:18:58.620 回答
1

您可以创建自己的splitString功能。这是一个例子:

std::vector<std::string> splitString(std::string str, char splitter){
    std::vector<std::string> result;
    std::string current = ""; 
    for(int i = 0; i < str.size(); i++){
        if(str[i] == splitter){
            if(current != ""){
                result.push_back(current);
                current = "";
            } 
            continue;
        }
        current += str[i];
    }
    if(current.size() != 0)
        result.push_back(current);
    return result;
}

这是一个示例用法:

int main(){ 
    vector<string> result = splitString("This is an example", ' ');
    for(int i = 0; i < result.size(); i++)
        cout << result[i] << endl;

    return 0;
}

或者你想如何使用它:

int main(){
    vector<string> result = splitString("Hello world!", ' ');
    string str1 = result[0];
    string str2 = result[1];
    cout << str1 << endl;
    cout << str2 << endl;

    return 0;
}
于 2021-07-15T15:58:47.567 回答