c - 字符串回文函数

标签 c

有一个简短的问题。

所以我尝试在我的一个“初学者”程序中用 C 语言设计一个回文函数。

对于那些不知道回文是什么的人来说,基本上它是一组字符(通常是一个单词,但也可以是数字 - 尽管在这种情况下具体是单词),其前后拼写方式相同。

回文的例子 - wow, lol, aaafaaa, ...

所以你明白了。所以我从我的功能开始

int 回文(字符输入[]){

所以我的假设是,理想情况下我想遍历带有索引的字符串并逐个字母地比较它。

int palindrome(char input[]){
 int start = 0, length = 0, end;
 /* Until we reach end of the word */
 while (input[start++] != '\0'){
   length++;

   for(start = 0, end = length - 1; start = length / 2; end--){
   /*If they do not match, return 0 */
     if (input[start] != input[end]){
        return 0;
        break;
     }
   }
 }
return 1;
}

这就是我的回文函数的样子。现在我只想检查来自标准标准输入的用户输入。

所以我的主要功能是这样的

int main(){
char uInput[30];

/* Welcome user */
printf("Hello, please enter some text \n);
scanf("%29s", uInput);

if palindrome(uInput){
printf("The word: %s is a palindrome \n", uInput);
}

else {
printf("The word: %s is not a palindrome \n", uInput);
}

return 0;
}

非常简单的代码,不幸的是,我的结果是

"The word (word) is not a palindrome"

不管是不是回文。

所以我的功能可能完全有问题。我也知道这可以通过其他库来完成,例如 string.h 和其他库,但我个人更愿意以这种方式作为一种练习,而不是使用预定义的函数。

是的,我强烈怀疑我没有在函数中正确使用我的返回值,但我不确定它们的实际错误是什么。

最佳答案

回文函数有多个错误

我们可以使用单个循环而不是循环中的循环。还要注意 for 循环的终止条件 start != (length/2) 以及 startend 的增量。

还修复了一些编译错误。完整代码如下。

#include <stdio.h>
int palindrome(char input[]){
 int start = 0, length = 0, end;

 /* Until we reach end of the word */
 while (input[length] != '\0')
   length++;

 for(start = 0, end = length - 1; start != (length / 2); start++, end--){
 /*If they do not match, return 0 */
     if (input[start] != input[end]){
        return 0;
     }
 }

 return 1;
}

int main(){
char uInput[30];

/* Welcome user */
printf("Hello, please enter some text \n");
scanf("%29s", uInput);

if (palindrome(uInput)){
printf("The word: %s is a palindrome \n", uInput);
}

else {
printf("The word: %s is not a palindrome \n", uInput);
}
return 0;
}

关于c - 字符串回文函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33480832/

相关文章:

c - 基本循环意外结束

c - 使用 C 使用 malloc 和 realloc 进行动态分配

c - 在 C 中哪里可以和不能声明新变量?

python - 从 Python 调用 C/C++ 代码

C结构: member order and memory allocation

c - 在 C 中将十进制数添加为字符串

c - 错误: Struct not defined correctly

c - 修复 BAC 程序

Objective-C,如何将文件名传递给 C 函数?

c - 带指针的结构体数组