[英]what is the best way to convert a char array (without null termination) to string
我有一個已知大小的char數組(例如10),我想將其轉換為strng。 要點是數組不是以NULL結尾的數組,因此無法使用以下示例代碼中使用的這項技術。
char arr[ ] = "This is a test";
string str(arr);
我可以做這個:
char * array=getArray();
string output;
for(int I=0;i<10;i++)
{
output.append(array[I]);
}
甚至更好的是:
char * array=getArray();
string output;
output.append(10,array);
但是,有什么更好的方法嗎?
如果沒有以nul結尾的字符串,但是知道字符串的長度,則可以使用兩個迭代器構造函數:
string str(arr, arr + len);
或適當的count構造函數:
string str(arr, len);
首先, "This is a test"
以 NIL
終止,並且第一個示例正常工作-編譯器隱式存儲零終止的字符串文字。
如果您的數組確實不是以NIL
終止的,則第三種方法會很好,而第二種方法效率不高,因為它是逐段追加的。 std::string
還有一個需要計數的構造函數: std::string(array, 10)
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.