Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Substring of char* to std::string

Tags:

c++

arrays

string

I have an array of chars and I need to extract subsets of this array and store them in std::strings. I am trying to split the array into lines, based on finding the \n character. What is the best way to approach this?

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);

Probably need some kind of interface like this:

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

like image 390
user807566 Avatar asked Sep 11 '25 09:09

user807566


2 Answers

I'd create the std::string as the first step, as splitting the result will be far easier.

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);
}
like image 157
Lightness Races in Orbit Avatar answered Sep 14 '25 01:09

Lightness Races in Orbit


You can use the std::string(const char *s, size_t n) constructor to build a std::string from the substring of a C string. The pointer you pass in can be to the middle of the C string; it doesn't need to be to the very first character.

If you need more than that, please update your question to detail exactly where your stumbling block is.

like image 37
Jonathan Grynspan Avatar answered Sep 13 '25 23:09

Jonathan Grynspan