[英]construct string from indices in C
When I construct a string like this: 当我构造这样的字符串时:
char string[1] = {'a'};
printf("%s", string)
it returns a a4
. 它返回
a4
。 Why is there a four at the end? 为什么末尾有四个? How can I get rid of it?
我该如何摆脱呢?
I choose this method because I need to make a string from character indexes, such as char array[4] = {string[i],string[j],string[k]};
我之所以选择这种方法,是因为我需要从字符索引中创建一个字符串,例如
char array[4] = {string[i],string[j],string[k]};
. 。
Your string should end with terminating char '\\0' You can do it by: 您的字符串应以终止字符'\\ 0'结尾。
char string[2] = {'a','\0'};
Or: 要么:
char string[] = "a";
"strings" in C are essentially arrays of characters ending with the \\0 character (null terminated). C语言中的“字符串”本质上是以\\ 0字符结尾的字符数组(空终止)。
So if you want an array of characters, what you did is fine, but it is not a "string". 因此,如果您想要一个字符数组,那么您所做的就可以了,但是它不是一个“字符串”。 Dont try to print it as such.
不要尝试这样打印。
If you would also like to print it or treat it as a "string", then increase it's length by 1, and add a '\\0'
char at the end. 如果您还想打印或将其视为“字符串”,则将其长度增加1,并在末尾添加一个
'\\0'
字符。
The conversion specification %s
is used to output strings that is a sequence of characters terminated by a zero character. 转换规范
%s
用于输出字符串,该字符串是一个以零个字符结尾的字符序列。
The array declared this way 数组以这种方式声明
char string[1] = {'a'};
does not contain a string. 不包含字符串。
So to output its elements you need to specify the exact number of characters you are going to output. 因此,要输出其元素,您需要指定要输出的确切字符数。 For example
例如
printf("%*.*s", 1, 1, string);
Otherwise reserve one more element in the array for the terminating zero and use the conversion specification %s
. 否则,在数组中为终止的零保留一个以上的元素,并使用转换规范
%s
。 For example 例如
char string[2] = {'a'};
printf( "%s", string );
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.