[英]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. 我有一个已知大小的char数组(例如10),我想将其转换为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.
要点是数组不是以NULL结尾的数组,因此无法使用以下示例代码中使用的这项技术。
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: 如果没有以nul结尾的字符串,但是知道字符串的长度,则可以使用两个迭代器构造函数:
string str(arr, arr + len);
or the appropriate count constructor: 或适当的count构造函数:
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. 首先,
"This is a test"
以 NIL
终止,并且第一个示例正常工作-编译器隐式存储零终止的字符串文字。
If your array really is not NIL
-terminated, the third approach will be good while the second is rather inefficient because it appends piecewise. 如果您的数组确实不是以
NIL
终止的,则第三种方法会很好,而第二种方法效率不高,因为它是逐段追加的。 std::string
also has a constructor that takes a count: std::string(array, 10)
. std::string
还有一个需要计数的构造函数: std::string(array, 10)
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.