Originally posted by sjalesho
I don't understand this part:
Code:
for(i = 0; i < (len / 2); i++)
{
char ch = str[i];
str[i] = str[(len - 1) - i];
str[(len - 1) - i] = ch;
}
Could someone please explain it to me so I can understand it?
The three lines in the loop body swap characters. For example:
Code:
str[] = "world"
len = 5
len / 2 = 2
str[0] str[1] str[2] str[3] str[4] str[5]
'w' 'o' 'r' 'l' 'd' '\0'
^ ^ ^ ^
| | | |
| +----- i=1 -----+ | (len - 1) - i = (5 - 1) - 1 = 4 - 1 = 3
| |
+------------- i=0 -------------+ (len - 1) - i = (5 - 1) - 0 = 4 - 0 = 4
Using a temporary variable to help simplify the end character index, and adding printfs, as previously suggested, you might have something like this.
Code:
#include <stdio.h>
#include <string.h>
void reverse_string(char str[])
{
int i, len = strlen(str);
printf("str = \"%s\", len = %d\n", str, len);
for ( i = 0; i < (len / 2); i++ )
{
char ch;
int x = (len - 1) - i;
printf("i = %d, x = %d: str[i] = '%c' <-> str[x] = '%c' -> ",
i, x, str[i], str[x]);
ch = str[i];
str[i] = str[x];
str[x] = ch;
printf("str = \"%s\"\n", str);
}
}
int main()
{
char str[] = "programmer";
reverse_string(str);
printf("%s\n", str);
return 0;
}
/* my output
str = "programmer", len = 10
i = 0, x = 9: str[i] = 'p' <-> str[x] = 'r' -> str = "rrogrammep"
i = 1, x = 8: str[i] = 'r' <-> str[x] = 'e' -> str = "reogrammrp"
i = 2, x = 7: str[i] = 'o' <-> str[x] = 'm' -> str = "remgramorp"
i = 3, x = 6: str[i] = 'g' <-> str[x] = 'm' -> str = "remmragorp"
i = 4, x = 5: str[i] = 'r' <-> str[x] = 'a' -> str = "remmargorp"
remmargorp
*/