如何将内容从一个字符串向量复制到另一个字符串向量

How can I copy content from one string vector to another?

本文关键字:向量 字符串 一个 复制 另一个      更新时间:2023-10-16

例如,我有一个基于字符串的向量:

vector<string> text_vec;

每个字符串中存储了几个单词。因此,我需要将每个单词从此向量复制到另一个字符串向量,但我应该将每个单词放在单独的字符串中。我该怎么做?

你的意思是你的矢量内容看起来像这样?

{ "word0", "word1 word2 word3", "word4 word5" }

你想要这样的结果:

{ "word0", "word1", "word2", "word3", "word4", "word5" }

首先重要的是定义什么构成一个词。我假设一个单词是由至少一个空格分隔的所有内容。在实践中,您可能需要处理一些特殊情况,例如:

  • 空字符串。
  • 其他空格字符。
  • 换行符。

让我们首先定义一个字符串拆分函数,该函数接受std::string并返回std::vector<std::string>。它将首先使用上述假设提供简单的拆分;您可以稍后使其更加复杂:

std::vector<std::string> split(std::string const& input)
{
    std::vector<std::string> result;
    std::istringstream is(input);
    std::string word;
    while (is >> word)
    {
        result.push_back(word);
    }
    return result;
}

有了这个函数,我们可以将其应用于您的输入向量:

std::vector<std::string> normalise(std::vector<std::string> const& strings)
{
    std::vector<std::string> result;
    for (auto const& string : strings)
    {
        auto const tokens = split(string);
        for (auto const& token : split(string))
        {
            result.push_back(token);
        }
    }
    return result;
}

这是一个完整的测试程序:

#include <iostream>
#include <string>
#include <vector>
#include <sstream>
std::vector<std::string> split(std::string const& input)
{
    std::vector<std::string> result;
    std::istringstream is(input);
    std::string word;
    while (is >> word)
    {
        result.push_back(word);
    }
    return result;
}
std::vector<std::string> normalise(std::vector<std::string> const& strings)
{
    std::vector<std::string> result;
    for (auto const& string : strings)
    {
        auto const tokens = split(string);
        for (auto const& token : split(string))
        {
            result.push_back(token);
        }
    }
    return result;
}
int main()
{
    std::vector<std::string> const input = { "word0", "word1 word2 word3", "word4 word5" };
    for (auto const& word : normalise(input))
    {
        std::cout << word << "n";
    }
}
vector<string> text_vec_2;
for(unsigned int i=0;i<text_vec.size();++i){
     // assuming a split-function which you have created
     // which returns a vector with the individual words
    vector<string> words = splitString(text_vec[i]);
    // copy the words into the new vector
    for(unsigned int j=0;j<words.size();++j){
        text_vec_2.push_back(words[j]);
    }
}