char*到std :: string的子串

use*_*566 2 c++ arrays string

我有一个chars 数组,我需要提取这个数组的子集并将它们存储在std::strings中.我试图基于找到\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);
Run Code Online (Sandbox Code Playgroud)

可能需要这样的界面:

std::string line = GetSubstring(char* src, int begin, int end);

Lig*_*ica 8

我创建了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);
}
Run Code Online (Sandbox Code Playgroud)


Jon*_*pan 5

您可以使用std::string(const char *s, size_t n)构造函数std::string从C字符串的子字符串构建a .传入的指针可以是C字符串的中间位置; 它不需要是第一个角色.

如果您需要更多,请更新您的问题以详细说明您的绊脚石的位置.