如何将内容从一个字符串向量复制到另一个字符串向量
How can I copy content from one string vector to another?
例如,我有一个基于字符串的向量:
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]);
}
}
相关文章:
- 在for循环中使用auto vs decltype(vec.size())来处理字符串的向量
- 构造<int>具有 2 个字符串文字的向量
- 如何将元素添加到向量的字符串位置
- 将向量解析<string>为字符串
- C ++中的StringStream有助于使用向量从字符串中提取逗号分隔的整数,而不是空格分隔的整数,为什么?
- 在 C++11 中,如何查找并返回以给定字符串开头的字符串向量中的所有项?
- 如何使用向量字符串令牌构建表达树
- 将 argv 复制到新的全局向量字符串
- 如何读取控制台输入并将其存储到向量字符串中
- 向量字符串push_back在C 中不起作用
- C char数组和向量字符串
- 可以直接初始化向量<字符串 *> 而不使用 new 吗?
- 迭代向量字符串的字符(C++禁止指针和整数之间的比较)
- 比较两个向量字符串的相似性C++
- 我有麻烦将字符串放入向量字符串
- 如何从一个向量字符串得到一个字符串的联合集
- 函数返回向量/字符串,但不返回数组
- 向量向量字符串固定大小
- c++向量字符串排序不工作
- C++将字符串数组[]复制到向量<字符串>