[英]How to concatenate string and int in C?
我需要在循環的每次迭代中形成一個字符串,其中包含循環索引i
:
for(i=0;i<100;i++) {
// Shown in java-like code which I need working in c!
String prefix = "pre_";
String suffix = "_suff";
// This is the string I need formed:
// e.g. "pre_3_suff"
String result = prefix + i + suffix;
}
我嘗試使用strcat
和itoa
各種組合而沒有運氣。
字符串在C中很辛苦。
#include <stdio.h>
int main()
{
int i;
char buf[12];
for (i = 0; i < 100; i++) {
snprintf(buf, 12, "pre_%d_suff", i); // puts string into buffer
printf("%s\n", buf); // outputs so you can see it
}
}
的12
是足夠的字節存儲文本"pre_"
,文本"_suff"
,最多兩個字符(串"99"
),並且繼續C字符串緩沖區的端NULL結束。
這將告訴你如何使用snprintf
,但我建議一本好的C書!
使用格式字符串"pre_%d_suff"
sprintf
(或snprintf
如果像我一樣,你不能計算)。
對於它的價值,使用itoa / strcat你可以做到:
char dst[12] = "pre_";
itoa(i, dst+4, 10);
strcat(dst, "_suff");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.