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

Substring of char* to std::string

本文关键字:字符串 string char std      更新时间:2023-10-16

我有一个char s数组,我需要提取该数组的子集并将它们存储在std::string s中。我试图将数组分成行,基于找到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 = 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);
}

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

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

我没有意识到您只希望一次处理每行,但是如果您需要一次处理所有行,您也可以这样做:

std::vector<std::string> lines;
char *s = buffer;
char *head = s;
while (*s) { 
  if (*s == 'n') { // Line break found
    *s = ''; // 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对象。

您的最佳选择(最佳含义最简单)是使用strtok并通过构造函数将令牌转换为std::string。(请注意,纯strtok是不可重入的,因此您需要使用非标准的strtok_r)。

void ProcessTextBlock(char* str)
{
    std::vector<std::string> v;
    char* tok = strtok(str,"n");
    while(tok != NULL)
    {
        ProcessLine(std::string(tok));
        tok = strtok(tok,"n");
    }
}

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

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

就像这样做:

char *cstr = "abcd";
std::string str(cstr + 1, cstr + 3);

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