模拟strrev()函数,疯狂输出
Simulate strrev() function, crazy output
我应该用我的题词模拟 strrev() 函数的操作。但是,我不明白为什么我有一系列特殊字符在您完全停止程序之前作为输出没有意义。我还尝试查看问题是否出在带有注释代码行的索引“i”中,但没问题。可能是什么问题呢?谢谢!
void strrev_new(char *s_to_rev) {
int i = 0;
int length = 0;
length = strlen(s_to_rev);
for (i = 0; i < length; i++) {
s_to_rev[length - i] = s_to_rev[i];
// printf("%d ----- %d\n", (length-i), i);
}
}
你有一个 off-by-one 错误,因为 strlen()
returns 字符串的长度(例如 hello
为 5),但字符串中的最后一个索引是4(从 0 开始计数)。
尝试
s_to_rev[length - 1 - i] = s_to_rev[i];
您的代码有两个问题。第一个,@AKX 出色地发现,你从 str[length]
字符而不是 str[length-1]
开始写(在 C 数组索引中从 0 开始)。
第二个问题是由于您试图就地反转字符串,即不使用辅助数组。
用循环
for (i = 0; i < length; i++) {
s_to_rev[length - i] = s_to_rev[i];
}
您正确地开始更新数组的最后一个元素。但是一旦你到达字符串的一半,s_to_rev[i]
处的字符就不再是原来的字符了,因为你之前更新过它们!
尝试遍历一半字符串并交换字符(只需使用临时 char
变量):
for (i = 0; i < length/2; i++) {
char tmp = s_to_rev[length - i -1],
s_to_rev[length - i -1] = s_to_rev[i];
s_to_rev[i] = tmp;
}
我应该用我的题词模拟 strrev() 函数的操作。但是,我不明白为什么我有一系列特殊字符在您完全停止程序之前作为输出没有意义。我还尝试查看问题是否出在带有注释代码行的索引“i”中,但没问题。可能是什么问题呢?谢谢!
void strrev_new(char *s_to_rev) {
int i = 0;
int length = 0;
length = strlen(s_to_rev);
for (i = 0; i < length; i++) {
s_to_rev[length - i] = s_to_rev[i];
// printf("%d ----- %d\n", (length-i), i);
}
}
你有一个 off-by-one 错误,因为 strlen()
returns 字符串的长度(例如 hello
为 5),但字符串中的最后一个索引是4(从 0 开始计数)。
尝试
s_to_rev[length - 1 - i] = s_to_rev[i];
您的代码有两个问题。第一个,@AKX 出色地发现,你从 str[length]
字符而不是 str[length-1]
开始写(在 C 数组索引中从 0 开始)。
第二个问题是由于您试图就地反转字符串,即不使用辅助数组。
用循环
for (i = 0; i < length; i++) {
s_to_rev[length - i] = s_to_rev[i];
}
您正确地开始更新数组的最后一个元素。但是一旦你到达字符串的一半,s_to_rev[i]
处的字符就不再是原来的字符了,因为你之前更新过它们!
尝试遍历一半字符串并交换字符(只需使用临时 char
变量):
for (i = 0; i < length/2; i++) {
char tmp = s_to_rev[length - i -1],
s_to_rev[length - i -1] = s_to_rev[i];
s_to_rev[i] = tmp;
}