[英]Printing a reversed string/array in C
I'm trying to print a reversed string/array. 我正在尝试打印反向的字符串/数组。 I've used the following code and it seems to be able to give my second array,
revString
, values in the correct order from the first array string
. 我使用了以下代码,它似乎能够按照第一个数组
string
的正确顺序提供第二个数组revString
值。 I am also able to print individual characters in both arrays, and I'm able to print the entire string of the first array. 我还可以在两个数组中打印单个字符,并且可以打印第一个数组的整个字符串。 However the
revString
array doesn't print at all. 但是
revString
数组根本不打印。 I'm wondering if I am missing a huge point here. 我想知道我是否在这里遗漏了一个要点。
void reverseString(char string[]) {
int i = strlen(string);
int i_2 = 0;
revString arrayet
char revString[i + 1];
char *character;
while (i > -1) {
character = &string[i];
revString[i_2] = *character;
printf("%c", revString[i_2]);
i = i - 1;
i_2 = i_2 + 1;
}
revString[i_2] = '\0';
printf("%d\n", i_2);
printf("%s", revString);
}
The code gives now the following output with example string "Hello World"
; 代码现在给出以下输出,并带有示例字符串
"Hello World"
;
dlrow olleH13
As you can see the final printf
statement doesn't do anything 如您所见,最终的
printf
语句不执行任何操作
In C language indexing is 0 based. 在C语言中,索引基于0。 so, if you make a string of 10 length, the last character will be at index 9.
因此,如果您输入长度为10的字符串,则最后一个字符将位于索引9处。
In your code, when you are assigning characters to revString, your code is trying to access string[len]. 在您的代码中,当您为revString分配字符时,您的代码正在尝试访问string [len]。
your code should be like this.. 您的代码应如下所示。
int i = strlen(string) - 1;
Your code reverses the string string
including the null terminator at string[i]
. 您的代码反转了字符串
string
其中string[i]
处包含空终止string[i]
。 The resulting array starts with a null terminator, hence printf
outputs nothing. 结果数组以空终止符开头,因此
printf
输出任何内容。
Here is a modified version: 这是修改后的版本:
void reverseString(char string[]) {
int i = strlen(string);
int i_2 = 0;
char revString[i + 1];
char character;
while (i > 0) {
i = i - 1;
character = string[i];
revString[i_2] = character;
//printf("%c", revString[i_2]);
i_2 = i_2 + 1;
}
revString[i_2] = '\0';
printf("%d\n", i_2);
printf("%s", revString);
}
Output: 输出:
11
dlrow olleH
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.