文字列とchar*変数に整数変数を追加するにはどうすればよいですか?例:
int a = 5;
文字列St1="Book"、St2;
char * Ch1 = "注"、Ch2;
St2 = St1 + a-> Book5
Ch2 = Ch1 + a-> Note5
ありがとう
これを行うC++の方法は次のとおりです。
std::stringstream temp;
temp << St1 << a;
std::string St2 = temp.str();
同じことをCh1
:で行うこともできます
std::stringstream temp;
temp << Ch1 << a;
char* Ch2 = new char[temp.str().length() + 1];
strcpy(Ch2, temp.str().c_str());
char*
たとえば、両方に十分な長さの別の変数を作成する必要があるためです。出力文字列の長さを「修正」して、文字列の終わりをオーバーランする可能性を排除できます。その場合は、整数を保持するのに十分な大きさにするように注意してください。そうしないと、book+50とbook+502の両方がbook+50(切り捨て)として出力される可能性があります。
必要なメモリ量を手動で計算する方法は次のとおりです。これは最も効率的ですが、エラーが発生しやすくなります。
int a = 5;
char* ch1 = "Book";
int intVarSize = 11; // assumes 32-bit integer, in decimal, with possible leading -
int newStringLen = strlen(ch1) + intVarSize + 1; // 1 for the null terminator
char* ch2 = malloc(newStringLen);
if (ch2 == 0) { exit 1; }
snprintf(ch2, intVarSize, "%s%i", ch1, a);
ch2には、結合されたテキストが含まれるようになりました。
または、少しトリッキーでなく、よりきれいな(ただし効率は低い)printfの「試行実行」を実行して、必要な長さを取得することもできます。
int a = 5;
char* ch1 = "Book";
// do a trial run of snprintf with max length set to zero - this returns the number of bytes printed, but does not include the one byte null terminator (so add 1)
int newStringLen = 1 + snprintf(0, 0, "%s%i", ch1, a);
char* ch2 = malloc(newStringLen);
if (ch2 == 0) { exit 1; }
// do the actual printf with real parameters.
snprintf(ch2, newStringLen, "%s%i", ch1, a);
プラットフォームにasprintfが含まれている場合、asprintfは新しい文字列に正しい量のメモリを自動的に割り当てるため、これははるかに簡単です。
int a = 5;
char* ch1 = "Book";
char* ch2;
asprintf(ch2, "%s%i", ch1, a);
ch2には、結合されたテキストが含まれるようになりました。
c ++はそれほど面倒ではありませんが、説明は他の人に任せます。
元の文字列とそれに続く数字を保持するのに十分な大きさの別の文字列を作成する必要があります(つまり、数字の各桁に対応する文字をこの新しい文字列に追加します)。
Try this out:
char *tmp = new char [ stelen(original) ];
itoa(integer,intString,10);
output = strcat(tmp,intString);
//use output string
delete [] tmp;