It is working exactly as you told it to work. Your cycle must be up to length/2
and not length
.
C reverse a string not working
Question
Could someone look over this code and check if it should work or not
Its supposed to reverse an entered string (for example "hello" should become "olleh")
void stringReverse (char string1[])
{
int length, i, j, k;
char tmp;
length = strlen(string1);
j = length - 1;
printf("Length: %i",length);
for (i = 0; i < length; i++)
{
tmp = string1[j];
string1[j] = string1[i];
string1[i] = tmp;
j--;
}
}
La solution
Autres conseils
char* strrev(char* s) {
char* h = s;
char* t = s;
char ch; `
while(*t++){};
t -= 2;
while(h < t){
ch = *h;
*h++ = *t; /* h向尾部移动 */
*t-- = ch; /* t向头部移动 */
}
return(s);
}
function: strrev
. This is implementation.
Hope this could help you.
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow