简体   繁体   中英

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?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM