Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert char* to string C++

Tags:

c++

string

char

I know the starting address of the string(e.g., char* buf) and the max length int l; of the string(i.e., total number of characters is less than or equal to l).

What is the simplest way to get the value of the string from the specified memory segment? In other words, how to implement string retrieveString(char* buf, int l);.

EDIT: The memory is reserved for writing and reading string of variable length. In other words, int l;indicates the size of the memory and not the length of the string.

like image 841
Terry Li Avatar asked Dec 08 '11 22:12

Terry Li


People also ask

Can you convert char * to string?

We can convert a char to a string object in java by using the Character. toString() method.

Is a char pointer a string?

A pointer may be defined as pointing to a character string. Remember that if the declaration is, char *pointer = "Sunday"; then the null character { '\0' } is automatically appended to the end of the text string.


1 Answers

std::string str(buffer, buffer + length); 

Or, if the string already exists:

str.assign(buffer, buffer + length); 

Edit: I'm still not completely sure I understand the question. But if it's something like what JoshG is suggesting, that you want up to length characters, or until a null terminator, whichever comes first, then you can use this:

std::string str(buffer, std::find(buffer, buffer + length, '\0')); 
like image 90
Benjamin Lindley Avatar answered Sep 20 '22 17:09

Benjamin Lindley