c++ - char* 到 std::string 的子串

标签 c++ arrays string

我有一个 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/

相关文章:

c++ - 收集唯一的排序 vector

c++ - C/C++标准库中的缓冲

具有重复外观的两个字符之间的 Java 正则表达式模式

c - 这个程序主要做什么?指针减法?

python - 编译支持GPU的Tensorflow时,遇到CUDA_TOOLKIT_PATH未绑定(bind)变量

c++ - 如何降低应用程序的 CPU 使用率?

c++ - 从 C++ 中的方法访问指向对象的私有(private)指针数组

javascript - 在 Javascript 文件中使用 AngularJS 过滤数组

javascript - 返回输入数组的最大元素的函数

javascript - 使用正则表达式操作字符串