我需要在循环的每次迭代中形成一个字符串,其中包含循环索引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;
}
Run Code Online (Sandbox Code Playgroud)
我试图使用的各种组合strcat
,并itoa
没有运气.
Lig*_*ica 97
字符串在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
}
}
Run Code Online (Sandbox Code Playgroud)
的12
是足够的字节来存储文本"pre_"
,文本"_suff"
,最多两个字符(串"99"
),并且继续C字符串缓冲区的端NULL结束.
这将告诉你如何使用snprintf
,但我建议一本好的C书!
使用sprintf
(或者snprintf
如果像我一样,你不能计算)格式字符串"pre_%d_suff"
.
对于它的价值,使用itoa/strcat你可以做到:
char dst[12] = "pre_";
itoa(i, dst+4, 10);
strcat(dst, "_suff");
Run Code Online (Sandbox Code Playgroud)