C++ char*到std::string的子字符串

C++ char*到std::string的子字符串,c++,arrays,string,C++,Arrays,String,我有一个字符数组,我需要提取这个数组的子集并将它们存储在std::string中。我正试图根据查找的字符\n将数组拆分为行。最好的方法是什么 int size = 4096; char* buffer = new char[size]; // ...Array gets filled std::string line; // Find the chars up to the next newline, and store them in "line" ProcessLine(line); 可能

我有一个字符数组,我需要提取这个数组的子集并将它们存储在std::string中。我正试图根据查找的字符\n将数组拆分为行。最好的方法是什么

int size = 4096;
char* buffer = new char[size];
// ...Array gets filled
std::string line;
// Find the chars up to the next newline, and store them in "line"
ProcessLine(line);
可能需要这样的接口:

std::string line=GetSubstringchar*src,int-begin,int-end

您可以使用std::stringconst char*s,size\t n构造函数从C字符串的子字符串构建std::string。您传入的指针可以指向C字符串的中间;它不需要是第一个字符


如果您需要更多信息,请更新您的问题,以详细说明您的绊脚石在哪里。

您最好的选择是通过构造函数使用令牌并将其转换为std::string。请注意,纯strtok不是可重入的,因此需要使用非标准strtok\u r

我将创建std::string作为第一步,因为拆分结果将容易得多

int size = 4096;
char* buffer = new char[size];
// ... Array gets filled
// make sure it's null-terminated
std::string lines(buffer);

// Tokenize on '\n' and process individually
std::istringstream split(lines);
for (std::string line; std::getline(split, line, '\n'); ) {
   ProcessLine(line);
}

我不知道您只想一次处理一行,但为了防止您同时需要所有行,您也可以这样做:

std::vector<std::string> lines;

char *s = buffer;
char *head = s;
while (*s) { 
  if (*s == '\n') { // Line break found
    *s = '\0'; // Change it to a null character
    lines.push_back(head); // Add this line to our vector
    head = ++s;
  } else s++; // 
}
lines.push_back(head); // Add the last line

std::vector<std::string>::iterator it;
for (it = lines.begin(); it != lines.end(); it++) {
  // You can process each line here if you want
  ProcessLine(*it);
}
// Or you can process all the lines in a separate function:
ProcessLines(lines);

// Cleanup
lines.erase(lines.begin(), lines.end());

我已经修改了缓冲区,vector.push_back方法自动从每个生成的C子字符串生成std::string对象。

您可以使用std::string的构造函数将char*子字符串转换为std::string:

template< class InputIterator >
basic_string( InputIterator first, InputIterator last, const Allocator& alloc = Allocator() );

在这种情况下,str将是bc。

可能不是最快的方法,但这也是我的第一种方法。它是最快的编写方法。可能不是跑得最快的。不是一直都是这样吗我喜欢std::string行的代码;std::getlinesplit,第“\n”行。美好的我想这可能对我有用。等我有时间的时候,再过几个小时我就要胡闹了。谢谢。@Jason:仅供参考。在getline时写入。。。相反,strtok的第一个参数是char*,而不是const char*@Steve:这对这个答案有什么影响?strtok是一个可怕的函数,因为它改变了输入。在C++中有很多更好的方法来做这件事。@马丁:当我写这个时我的大脑处于C模式,所以只要快速和肮脏的东西就不需要保存字符串。Tomalak:我不小心做了param const char*完全是出于习惯,一分钟后就修好了,这就是Steve看到的。谢谢,类似于:string&buffer[10],20?由于某种原因,当我尝试这个时,我得到了非常差的性能。嗯,你的用例不清楚。你一秒钟做一百万次吗?两次什么定义性能差。
template< class InputIterator >
basic_string( InputIterator first, InputIterator last, const Allocator& alloc = Allocator() );
char *cstr = "abcd";
std::string str(cstr + 1, cstr + 3);