C 反向字符串[暂停]
I have the following code where Index is defined as length- 1. It prints an extra space in the beginning if I dont include the - 1. Why is the -1 required in the code?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char s[200];
int index, lenght;
printf("Input a string\n");
gets(s);
// Calculating string length
length = strlen(s);
index=length-1;
while (index >=0) {
printf("%c", s[index]);
index--;
}
printf("\n");
return 0;
}
转载于:https://stackoverflow.com/questions/53038637/c-reverse-string
Indexes always start from 0
. So if strlen() function returns the length x
that means its length is x
and you have to iterate from 0 to x-1
. Thats why you have to include -1
. On index x there will be some garbage or space.
Let us take a string of length 5 -- abcde
. len
is 5.
while (index >=0) {
printf("%c", s[index]);
index--;
}
For the first element in the loop, you are printing s[index]
. You want to print e
i.e. s[4]
Therefore you need to set index as len-1
If not, you are printing s[5]
which is \0
, the NULL terminator.
You need to search the return-value about function strlen()
and You'll understand it.
The reason for that extra character in the beginning is that, the string is terminated with a NULL character. So if you store a string “abcdef” it will be stored as a,b,c,d,e,f,\0. Strlen will return the length of above string as 6. So if you start from printing array index 6, NULL is printed and so on. Hence the extra space. Using -1 makes you start printing from array index 5 (your data will be stored in array indexes 0-5) which is f in this case, so you need to use -1.