如何在C++中像Python一样分割字符串?

7

在Python中,您可以像这样拆分字符串:

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

然后它会打印出来:

Hello 
world!

我该如何在C++中做同样的事情?这篇文章并没有帮到我:Parse (split) a string in C++ using string delimiter (standard C++),我需要将它们分解开来,以便我可以单独访问它们,例如只打印 str1。

2
这个回答解决了你的问题吗?C++将字符串分割为vector<string> - zerocukor287
你所链接的问题中至少有一个答案可以返回一个向量。如果你想要Python元组解包,那就会变得更加棘手。C++有std::tie,但我认为它只适用于std::tuple。而在C++中处理这个可能并不容易。 - Fred Larson
6
有时候你必须放弃在 X 语言中编写代码的方式,去接受 Y 语言的惯用法。如果用 X 的方式很困难,就用 Y 的方式来做。 - user4581301
当有多个分隔符时,split函数会做什么?它总是在找到第一个分隔符时拆分并返回两个字符串吗?还是可能有更多的返回值? - 463035818_is_not_a_number
3
你应该专注于你想要使用的功能,而不仅仅是“我想在C++中做同样的事情”。几乎从来没有两个不同语言中的函数对所有输入都表现完全相同。如果你想要将字符串拆分成两个部分,这也可以在C++中完成。 - 463035818_is_not_a_number
显示剩余4条评论
4个回答

9
如果您的分词器始终为一个空格(" "),且您可能不会使用其他字符对字符串进行分词(例如 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!

@Bathsheba 修改为仅使用 std::string - aminrd
3
非常好,谢谢。我改变了我的投票,从负面转为正面。相对于一堆繁琐的分割代码,这种方式更加可取。 - Bathsheba
也许strtok是一个更通用的答案?! - IMAN4K
@IMAN4K:strtok可能会形成一个更一般的答案,但我喜欢这个答案的特定性以及strtok是魔鬼的缩小版本的事实。 - Bathsheba
没有stringstream头文件。应该是sstream - undefined
@rosshjb 修改完毕! - undefined

2
你可以创建自己的 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;
}

这不是错误的,但如果这是 OP 想要的,那么已经有重复的问题和答案在这里:https://stackoverflow.com/questions/43751221/c-split-string-to-vectorstring 和其他地方。 - 463035818_is_not_a_number

1
使用boost:
#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


0
#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;
}

在找到“/”或“+”时,将字符串中给定的所有数字拆分开。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接