web-dev-qa-db-ja.com

char *を文字列C ++に変換します

文字列の開始アドレス(_char* buf_など)と文字列の最大長__int l;_(つまり、文字の総数がl以下)を知っています。

指定したメモリセグメントからstringの値を取得する最も簡単な方法は何ですか?つまり、string retrieveString(char* buf, int l);の実装方法。

[〜#〜] edit [〜#〜]:メモリは、可変長の文字列を読み書きするために予約されています。つまり、_int l;_は、文字列の長さではなく、メモリのサイズを示します。

27
Terry Li
std::string str(buffer, buffer + length);

または、文字列が既に存在する場合:

str.assign(buffer, buffer + length);

編集:質問を理解したかどうかはまだ完全にはわかりません。ただし、JoshGが提案しているようなもので、length文字まで、またはヌルターミネータまでのいずれかが先に来た場合、これを使用できます。

std::string str(buffer, std::find(buffer, buffer + length, '\0'));
19
char *charPtr = "test string";
cout << charPtr << endl;

string str = charPtr;
cout << str << endl;
8
Taha

あなたの説明にはいくつかの詳細が残されているようですが、ベストを尽くします...

これらがNULで終了する文字列であるか、メモリが事前にゼロに設定されている場合、NUL(0)文字または最大長(どちらか早い方)に達するまでメモリセグメントの長さを反復することができます。文字列コンストラクターを使用して、バッファーと前の手順で決定したサイズを渡します。

string retrieveString( char* buf, int max ) {

    size_t len = 0;
    while( (len < max) && (buf[ len ] != '\0') ) {
        len++;
    }

    return string( buf, len );

}

上記が当てはまらない場合、文字列の終了位置をどのように判断するかわかりません。

2

文字列のコンストラクターを使用する

basic_string(const charT* s,size_type n, const Allocator& a = Allocator());

編集:

OK、C文字列の長さが明示的に指定されていない場合は、ctorを使用します。

basic_string(const charT* s, const Allocator& a = Allocator());
2
chill
_std::string str;
char* const s = "test";

str.assign(s);
_

string& assign (const char* s); => signature FYR

Reference/s ここ

0
parasrish