次のように 2 つの const char を連結する必要があります。
const char *one = "Hello ";
const char *two = "World";
どうすればそれを行うことができますか?
これらchar*
の s は、C インターフェイスを備えたサードパーティ ライブラリから渡されたため、単純std::string
に代わりに使用することはできません。
次のように 2 つの const char を連結する必要があります。
const char *one = "Hello ";
const char *two = "World";
どうすればそれを行うことができますか?
これらchar*
の s は、C インターフェイスを備えたサードパーティ ライブラリから渡されたため、単純std::string
に代わりに使用することはできません。
あなたの例では、 1 つ目と2 つ目は char ポインターであり、char 定数を指しています。これらのポインターが指す char 定数を変更することはできません。だから次のようなもの:
strcat(one,two); // append string two to string one.
動作しないでしょう。代わりに、結果を保持する別の変数 (char 配列) が必要です。このようなもの:
char result[100]; // array to hold the result.
strcpy(result,one); // copy string one into the result.
strcat(result,two); // append string two to the result.
C の方法:
char buf[100];
strcpy(buf, one);
strcat(buf, two);
C++ の方法:
std::string buf(one);
buf.append(two);
コンパイル時の方法:
#define one "hello "
#define two "world"
#define concat(first, second) first second
const char* buf = concat(one, two);
C++ を使用している場合はstd::string
、C スタイルの文字列の代わりに使用してみませんか?
std::string one="Hello";
std::string two="World";
std::string three= one+two;
この文字列を C 関数に渡す必要がある場合は、単純に渡します。three.c_str()
使用std::string
:
#include <string>
std::string result = std::string(one) + std::string(two);
const char *one = "Hello ";
const char *two = "World";
string total( string(one) + two );
// to use the concatenation as const char*, use:
total.c_str()
更新:パフォーマンス上の理由から に変更さ
string total = string(one) + string(two);
れました (文字列 2 と一時的な文字列合計の構築を回避します)string total( string(one) + two );
// string total(move(move(string(one)) + two)); // even faster?
もう 1 つの例:
// calculate the required buffer size (also accounting for the null terminator):
int bufferSize = strlen(one) + strlen(two) + 1;
// allocate enough memory for the concatenated string:
char* concatString = new char[ bufferSize ];
// copy strings one and two over to the new buffer:
strcpy( concatString, one );
strcat( concatString, two );
...
// delete buffer:
delete[] concatString;
ただし、特に C++ 標準ライブラリを使用したくない、または使用できない場合を除き、使用するstd::string
方がおそらく安全です。
C ライブラリで C++ を使用しているように思われるため、const char *
.
const char *
それらを次のようにラップすることをお勧めしstd::string
ます:
const char *a = "hello ";
const char *b = "world";
std::string c = a;
std::string d = b;
cout << c + d;
まず、動的メモリ空間を作成する必要があります。次に、2 つの文字列をその中に strcat するだけです。または、c++ の「string」クラスを使用できます。古い学校の C の方法:
char* catString = malloc(strlen(one)+strlen(two)+1);
strcpy(catString, one);
strcat(catString, two);
// use the string then delete it when you're done.
free(catString);
新しい C++ の方法
std::string three(one);
three += two;
使用できますstrstream
。正式には廃止されましたが、C 文字列を扱う必要がある場合は、依然として優れたツールだと思います。
char result[100]; // max size 100
std::ostrstream s(result, sizeof result - 1);
s << one << two << std::ends;
result[99] = '\0';
one
これは、その後two
ストリームに書き込み、終了\0
する using を追加しますstd::ends
。両方の文字列が正確に99
文字を書き込む可能性がある場合 (スペースが残っていないため\0
、最後の位置に手動で書き込みます)。
const char* one = "one";
const char* two = "two";
char result[40];
sprintf(result, "%s%s", one, two);