📜  字符串按空格分割 c++ (1)

📅  最后修改于: 2023-12-03 15:39:02.652000             🧑  作者: Mango

字符串按空格分割 C++

在 C++ 中,我们可以用以下方法将字符串按空格分割成单词:

方法一:使用 stringstream

首先,我们可以创建一个 stringstream 对象并将要分割的字符串作为输入流输入到其中。接下来,我们可以使用 while 循环从 stringstream 中逐个读取单词并将它们存储在一个向量或数组中。在 while 循环中,我们可以使用 getline() 函数以空格作为分隔符读取单个单词并将其添加到向量或数组中。最后,我们可以使用 size() 函数获取向量或数组的长度并将它们输出到屏幕上。以下是示例代码:

#include <iostream>
#include <vector>
#include <sstream>

using namespace std;

int main() {
    string str = "Hello world! This is a test string.";
    vector<string> words;
    stringstream ss(str);
    string word;

    while (getline(ss, word, ' ')) {
        words.push_back(word);
    }

    for (int i = 0; i < words.size(); i++) {
        cout << words[i] << endl;
    }

    cout << "The number of words: " << words.size() << endl;

    return 0;
}

输出结果为:

Hello
world!
This
is
a
test
string.
The number of words: 7
方法二:使用 strtok() 函数

另一种将字符串按空格分割的方法是使用 strtok() 函数。这个函数可以接受一个指向字符串的指针和一个分隔符作为参数,并返回指向分割后的子字符串的指针。我们可以进行多次调用,每次都将分隔符设置为一个空格,并将返回的子字符串添加到向量或数组中。最后,我们仍然可以使用 size() 函数获取向量或数组的长度并将它们输出到屏幕上。以下是示例代码:

#include <iostream>
#include <vector>
#include <cstring>

using namespace std;

int main() {
    string str = "Hello world! This is a test string.";
    char *s = new char[str.size() + 1];
    strcpy(s, str.c_str());
    vector<string> words;
    char *p = strtok(s, " ");

    while (p != NULL) {
        words.push_back(p);
        p = strtok(NULL, " ");
    }

    for (int i = 0; i < words.size(); i++) {
        cout << words[i] << endl;
    }

    cout << "The number of words: " << words.size() << endl;

    return 0;
}

输出结果与方法一相同。

以上就是将字符串按空格分割的两种方法。这两种方法都很简单易懂,可以根据自己的需求选择其中的一种。