用空格分隔字符串的最简单方法

Easiest way to separate a string by spaces?

本文关键字:最简单 方法 字符串 空格 分隔      更新时间:2023-10-16

我已经很久没有使用C++了,在我的空闲时间一直在使用Javascript,现在我不确定我到底记得什么。

基本上,我只需要通过查看空格将字符串分成几部分。

看到的所有链接都是自制函数,但我本可以发誓有一种方法可以通过使用流来使用标准库来做到这一点,但同样,我很难回忆起它,我的谷歌结果也没有帮助。

请记住,它不是我从中获取的流,它只是一个字符串,例如"Bob Accountant 65 retired",我必须将字符串中的每个项目提取到它自己的数据字段中。我一直在搞乱ifstreams和ofstreams,但我什至不确定我在做什么,忘记了它的语法。

std::strtok

C风格的方法。您可能正在考虑使用std::stringstream,例如:

#include <sstream>
#include <string>
#include <iostream>
int main() {
    std::string input = "foo bar baz  quxxnducks";
    std::stringstream ss(input);
    std::string word;
    while (ss >> word) {
        std::cout << word << 'n';
    }
}

运行时,将显示:

foo
bar
baz
quxx
ducks

如果你想将数据从std::stringstream(或任何类型的std::istream,实际上)读入特定的数据类型,你可以按照@JerryCoffin的优秀建议,为你的数据类型重载流operator>>

#include <sstream>
#include <string>
#include <iostream>
struct Employee {
    std::string name;
    std::string title;
    int age;
    std::string status;
};
std::istream& operator>>(std::istream &is, Employee &e) {
    return is >> e.name >> e.title >> e.age >> e.status;
}
int main() {
    std::string input = "Bob Accountant 65 retired";
    std::stringstream ss(input);
    Employee e;
    ss >> e;
    std::cout << "Name: " << e.name
        << " Title: " << e.title
        << " Age: " << e.age
        << " Status: " << e.status
        << 'n';
}

您可以在没有显式循环的情况下执行此操作,如下所示:

string s = "Bob Accountant 65 retired";
vector<string> vs;
istringstream iss(s);
copy(istream_iterator<string>(iss), istream_iterator<string>(), back_inserter(vs));

std::copy从在第三行创建的字符串流中读取所有内容,并将其推送到在第二行创建的向量中。

这是关于 ideone 的演示。

从外观上看,您正在尝试从字符串中读取逻辑记录。为此,我会做这样的事情:

struct record { 
    std::string name;
    std::string position;
    int age;
    std::string status;
};
std::istream &operator>>(std::istream &is, record &r) { 
    return i >> r.name >> r.position >> r.age >> r.status;
}

这使您可以将数据从stringstream读取到指定字段的record。顺便说一下,它还允许您从其他类型的流中读取record对象(例如,从使用 fstream 的文件)。