gpt4 book ai didi

c - 用 C 编写一个名为reverse_str 的函数,该函数采用单个 char * 参数并就地反转字符串

转载 作者:行者123 更新时间:2023-11-30 21:00:20 25 4
gpt4 key购买 nike

我是 C 程序新手,我尝试按照以下准则尝试练习问题。用 C 编写一个名为reverse_str 的函数,该函数采用单个 char * 参数并就地反转字符串。因此,如果 str 的值为:

char str[] = "Let's meet l8r 2nite?";

那么在调用reverse_str之后,str的值应该是:

"?etin2 r8l teem s'teL"

请记住,您的函数应与此原型(prototype)声明匹配:

void reverse_str(char *str);

说明:请勿假设已包含除 stdio.h 之外的任何库或头文件。仅使用标准 C(具体来说,不要使用任何 Microsoft 特定函数)。不要在函数中打印任何内容。您提交的内容应该只包含reverse_str函数,而不包含其他任何内容(具体来说,不要包含main函数)。

我在该网站尝试了这个解决方案

void reverse_str(char* str)
{
int i, slen = 0;
while (str[slen] != '\0')
{
slen++;
}

for (i = 0; i < (slen + 1) / 2; i++)
{
str[i] += str[slen];
str[slen] = str[i] - str[slen];
str[i] = str[i] - str[slen--];
}
}

但它给了我这种类型的消息

Sorry. Your solution is incorrect. Please try again. Feedback for your solution:

Your function does not work as expected. Please check the following carefully:

Does your function produce the output given in the problem? You should put your function in a full program, compile and run it and test it before submitting. (But submit only the function, not the full program.)

Your submission should only contain the function, the full function, and no other extra code. Specifically, it should not contain the main function, or any other #included files

Make sure that your submission does not contain any functions not found in the standard C library. Specifically, do not use any Microsoft specific functions.

Do not include conio.h and do not use functions like getch.Make sure you do not print anything. No printf or putc or puts.

你能告诉我正确的解决方案是什么吗

最佳答案

首先:i < (slen + 1) / 2 - 为什么+ 1 ?应该只是i < (slen) / 2因为在字符串长度为偶数的情况下,您需要迭代一半的字符串,而在长度为奇数时,您需要迭代半个字符(中间的字符不必与某些东西交换,因为它已经在它的位置上 - 正好中间)。

现在关于str[i] += str[slen]; , str[i] - str[slen];str[i] - str[slen--]; - 此处“减去”字符,因此结果无效。

您需要简单地交换字符,如下所示:

char swapCharacter = str[i];
str[i] = str[slen-i-1];
str[slen-i-1] = swapCharacter;

关于c - 用 C 编写一个名为reverse_str 的函数,该函数采用单个 char * 参数并就地反转字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42007142/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com