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

C++ 将std::string转换为c字符串数组,c++,C++,我试图找到一种方法,将字符串转换为c字符串数组。 例如,我的字符串是: std::string s = "This is a string." 然后我希望输出是这样的: array[0] = This array[1] = is array[2] = a array[3] = string. array[4] = NULL #include <boost/algorithm/string.hpp> std::vector<std::string> strs; boos

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

std::string s = "This is a string."
然后我希望输出是这样的:

array[0] = This
array[1] = is
array[2] = a
array[3] = string.
array[4] = NULL
#include <boost/algorithm/string.hpp>
std::vector<std::string> strs;
boost::split(strs, "string to split", boost::is_any_of(" "));
以你为例

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

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

//Let's say:
string s = "This is a string.";
//Therefore:
s[0] = T
s[1] = h
s[2] = i
s[3] = s
但根据你的例子

我想你想把文字分开。(以空间作为测力计)

您可以使用字符串的拆分函数

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

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

array[0] = This
array[1] = is
array[2] = a
array[3] = string.
array[4] = NULL
#include <boost/algorithm/string.hpp>
std::vector<std::string> strs;
boost::split(strs, "string to split", boost::is_any_of(" "));
#包括
std::载体strs;
boost::split(strs,“string to split”,boost::是(“”)的任意值;
然后在
strs
向量上迭代

这种方法允许您指定任意多的分隔符

请参见此处了解更多信息:


这里有很多方法:

您正在尝试将字符串拆分为字符串。尝试:

 #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;
  }
#包括
#包括
#包括
#包括
std::string s=“这是一个字符串。”;
std::矢量阵列;
标准::stringstream ss(s);
std::字符串tmp;
而(std::getline(ss,tmp,,))
{
阵列。推回(tmp);
}
for(auto it=array.begin();it!=array.end();+it)
{

std::cout这是一个字符串数组,而不是字符数组。所以你有一个
std::string
s的数组,就像
std::string字符串[5];
?您是在空格上拆分字符串,而不是转换为字符数组。第一个链接起作用,或者您可以搜索“拆分字符串c++”以找到所需内容。删除了c标记,因为问题在c中没有意义。在c中,字符串是字符数组,因此不需要进行转换。您必须透露是哪个字符串C++标准规定<代码>()/>代码>代码:ST::String 。这不是java。我尝试使用你的例子,但是我得到这个“错误:变量”STD::String String SS有初始化器但不完整类型。你需要包括必要的标题,见我的更新答案啊,我有其他3个我只是错过了sstream。非常感谢,这是一个很大的帮助。