我正在尝试编写一个函数来反转字符串:如果字符串输入是"Hello World"
,则函数应该返回"dlroW olleH"
。但是,当我运行我的函数时,字符串保持不变:
void reversestring(char* s) {
char tmp; //tmp storing the character for swaping
int length; //the length of the given string
int i; //loop counter
//reverse the string of even length
length = strlen(s);
if (length % 2 == 0) { //if the length of the string is even
for(i = 0; i < (int) (length / 2);i++) {
tmp = s[length - i];
s[length - i] = s[i];
s[i] = tmp;
}
}
//reverse the string of odd length
if (length % 2 == 1) { //if the length of the string is odd
for(i = 0; i < (int) ((length + 1) / 2);i++) {
tmp = s[length + 1];
s[length + 1] = s[i];
s[i] = tmp;
}
}
}