C字符串和INT串联 [英] c string and int concatenation
问题描述
这是谈到了将更难方式比它应该(我没有一个C背景):
This is turning out to be way harder than it should (I dont have a c background):
我需要形成一个字符串时,每次循环,它包含了循环索引中的 I
:
I need to form a string, inside each iteration of the loop, which contains the loop index 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
的各种组合,没有运气。
I tried using various combinations of strcat
and itoa
with no luck.
推荐答案
字符串在C艰苦的工作。
Strings are hard work in C.
int main()
{
int i;
char buf[12];
for (i = 0; i < 100; i++) {
sprintf(buf, "pre_%d_suff", i); // puts string into buffer
printf("%s\n", buf); // outputs so you can see it
}
}
的 12
是足够的字节用于存储文本pre _
,文字_ SUFF
,最多两个字符的字符串(99
)和那张C的结束NULL结束字符串缓冲区。
The 12
is enough bytes to store the text "pre_"
, the text "_suff"
, a string of up to two characters ("99"
) and the NULL terminator that goes on the end of C string buffers.
这将告诉你如何使用的sprintf
,但我建议一个好的C书!
This will tell you how to use sprintf
, but I suggest a good C book!
这篇关于C字符串和INT串联的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!