将std::字符串转换为c字符串数组

converting a std::string to an array of c strings

本文关键字:字符串 数组 转换 std      更新时间:2023-10-16

我正试图找到一种将字符串转换为c字符串数组的方法。例如,我的字符串是:

std::string s = "This is a string."

然后我希望输出是这样的:

array[0] = This
array[1] = is
array[2] = a
array[3] = string.
array[4] = NULL

您正试图将字符串拆分为多个字符串。尝试:

 #include <sstream>
 #include <vector>
 #include <iostream>
 #include <string>
 std::string s = "This is a string.";
  std::vector<std::string> array;
  std::stringstream ss(s);
  std::string tmp;
  while(std::getline(ss, tmp, ' '))
  {
    array.push_back(tmp);
  }
  for(auto it = array.begin(); it != array.end(); ++it)
  {
    std::cout << (*it) << std:: endl;
  }

或者查看此拆分

使用Boost库函数"Split"根据分隔符将字符串拆分为多个字符串,如下所示:

#include <boost/algorithm/string.hpp>
std::vector<std::string> strs;
boost::split(strs, "string to split", boost::is_any_of(" "));

然后对strs向量进行迭代。

这种方法允许您指定任意数量的分隔符。

查看此处了解更多信息:http://www.boost.org/doc/libs/1_48_0/doc/html/string_algo/usage.html#id3115768

这里有很多方法:用C++拆分字符串?

在您的示例中。

数组不是字符数组,而是字符串数组。

实际上,字符串是一个字符数组。

//Let's say:
string s = "This is a string.";
//Therefore:
s[0] = T
s[1] = h
s[2] = i
s[3] = s

但根据你的例子,

我想你想把文本分开。(以SPACE作为delimeter)。

您可以使用字符串的拆分功能。

string s = "This is a string.";
string[] words = s.Split(' ');
//Therefore:
words[0] = This
words[1] = is
words[2] = a
words[3] = string.