我有一个 char
数组,我需要提取这个数组的子集并将它们存储在 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);
可能需要这样的接口(interface):
std::string line = GetSubstring(char* src, int begin, int end);
最佳答案
我将创建 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);
}
关于c++ - char* 到 std::string 的子串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7066499/