简体   繁体   English

检查输入的单词是否是回文

[英]Checking whether the input word is a palindrome

Hello i am having an error when i try to compile my code. 您好,我尝试编译代码时遇到错误。

int main()
{

char string_buffer[20], string_buffer1[20];//which is going to be copied into and reversed.

printf("Enter the string to check if it is a palindrome\n");
scanf("%20s", string_buffer);

strcpy(string_buffer1,string_buffer);//copying string_buffer into string_buffer1
strrev(string_buffer1);//reverse string_buffer1

if (strcmp(string_buffer,string_buffer1) == 0){//check to see if they are the same
    printf("Palindrome.\n");

}else{
    printf("Not a palindrome.\n");

}       
    return 0;

}

When i try to compile i get this warning and error. 当我尝试编译时,出现此警告和错误。

palindrome.c:12:2: warning: implicit declaration of function 'strrev' is invalid
      in C99 [-Wimplicit-function-declaration]
        strrev(string_buffer1);//reverse string_buffer1
        ^
1 warning generated.
/tmp/palindrome-1efe10.o: In function `main':
palindrome.c:(.text+0x68): undefined reference to `strrev'
clang-3.5: error: linker command failed with exit code 1 (use -v to see invocation)

You don't have strrev in linux, use one of the alternatives (taken from here ): 您在Linux中没有strrev ,请使用一种替代方法(从此处获取 ):

#include <string.h>

char *strrev(char *str)
{
      char *p1, *p2;

      if (! str || ! *str)
            return str;
      for (p1 = str, p2 = str + strlen(str) - 1; p2 > p1; ++p1, --p2)
      {
            *p1 ^= *p2;
            *p2 ^= *p1;
            *p1 ^= *p2;
      }
      return str;
}

You don't need strrev or even require to duplicate the memory. 您不需要strrev甚至不需要复制内存。 The following code is a much simpler and a direct answer to your question. 以下代码是对您的问题的更简单直接的回答。 Please note that this code assumes that neither NULL nor "" are palindroms. 请注意,此代码假定NULL和“”都不是palindroms。 The function returns 1 if the passed string is a palindrome and 0 otherwise. 如果传递的字符串是回文,则该函数返回1,否则返回0。

int is_palindrome(const char *str)
{
    size_t len = str ? strlen(str) : 0;
    const char *p;

    if (len < 1)
            return 0;

    for (p = str + len - 1; str < p; str++, p--)
            if (*p != *str)
                    return 0;
    return 1;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM