mans
mans

Reputation: 18168

what is the best way to convert a char array (without null termination) to string

I have a char array with known size (say 10) and I want to convert it to a strng. The main point is the array is not NULL terminated so this technique that used in the following sample code can not be used.

char arr[ ] = "This is a test";

string str(arr);

I can do this:

 char * array=getArray();
 string output;
 for(int I=0;i<10;i++)
 {
    output.append(array[I]);
 }

or even better one is:

 char * array=getArray();
 string output;
  output.append(10,array);

But is there any better way to do this?

Upvotes: 2

Views: 2043

Answers (2)

juanchopanza
juanchopanza

Reputation: 227418

If you don't have a nul-terminated string, but you know its length, you can use either the two iterator constructor:

string str(arr, arr + len);

or the appropriate count constructor:

string str(arr, len);

Upvotes: 10

Alexander Gessler
Alexander Gessler

Reputation: 46607

First of all, "This is a test" is NIL-terminated and the first sample just works - the compiler implicitly stores string literals with zero termination.

If your array really is not NIL-terminated, the third approach will be good while the second is rather inefficient because it appends piecewise. std::string also has a constructor that takes a count: std::string(array, 10).

Upvotes: 3

Related Questions