回文C ++(strcpy)

时间:2015-10-06 16:36:01

标签: c++ arrays palindrome c-strings

我试图在互联网上找到解决方案但却找不到类似的东西。我正在使用strcpy和iteration在c ++中创建一个回文函数一切正常但是strcpy部分。我不知道如何解决它或使用其他替代品。谢谢。

#include <iostream>
#include <cstring>

using namespace std;

void palindrom(char[]);

int main()
{
   char binput[100];

   cout << "Hello please enter your word here: " << endl;    
   cin >> binput;
   palindrom(binput);

   system("pause");
   return 1;   
}

void palindrom(char binput[])
{
   int max= strlen(binput);
   char cinput[100];
   char dinput[100];

   for (int i=max, n=0; i>=0, n<=max; i--, n++)
      strcpy(dinput[n],binput[i]);

   cout << dinput << endl;

   if (strcmp(binput,dinput)==true)
      cout << "Is palindrome " << endl;
   else 
      cout << "Is not " << endl;
}

4 个答案:

答案 0 :(得分:0)

看起来你不清楚strcpy做了什么。它将整个字符串从源复制到目标。你不需要这个。你需要做简单的作业。

假设您的输入为"abc"。我假设您要从中创建字符串"abccba"

给出输入中的字符:

+---+---+---+
| a | b | c |
+---+---+---+

您需要将它们映射到输出数组:

binput[0]
|       binput[len-1]
|       |   binput[len-1]
| ....  |   |       binput[0]
|       |   | ....  |
v       v   v       v
+---+---+---+---+---+---+
| a | b | c | c | b | a |
+---+---+---+---+---+---+

现在,将该逻辑转换为代码:

int len= strlen(binput);
char dinput[100];

for (int i = 0; i < len; ++i )
{
   dinput[i] = binput[i];         // Takes care of the left side of the palindrome.
   dinput[2*len-i-1] = binput[i]; // Takes care of the right side of the palindrome
}

// Make sure to null terminate the output array.
dinput[2*len] = '\0';

更新,以回应OP的评论

你需要:

for (int i = 0; i < len; ++i )
{
   dinput[len-i-1] = binput[i];
}
dinput[len] = '\0';

答案 1 :(得分:0)

希望这可以解决。基本上首先只检查单词的第一个字母和最后一个字母。如果他们不平等,那么他们不是回文。如果它们相等,则继续比较前端字符和它们各自的后端。

#include<iostream>
#include<cstring>
using namespace std;

int CheckPalindrome(char input[],int len);


int main()
{
  char input[100];
  int result,inpLen;


  cout<<"Enter Word:"<<endl;
  cin>>input;
  cout<<"Entered Word:"<<input<<endl;
  cout<<"Checking....."<<endl;
  inpLen=strlen(input);
  result=CheckPalindrome(input,inpLen);
  if(result == 1)
  {
    cout<<"Entered Word:"<<input<<" is a palindrome!"<<endl;
  }
  else
  {
    cout<<"Entered Word:"<<input<<" is not a palindrome!"<<endl;
  }

 return 0;
}

int CheckPalindrome(char input[],int len)
{

   int result;

   if(input[0] != input[len-1])
   {
      result = 0;
   }
   else
   {
   for(int i=0 ; i<len ; i++)
   {
     if(input[i] == input[len-1-i])
     {
        result = 1;
     }
     else
     {
      result = 0;
      break;
     }
   }
  }

 return result;
}

答案 2 :(得分:0)

if(strcmp(word,strrev(word)==0)

Pallindrome

答案 3 :(得分:-1)

您应该将i初始化为max-1而不是max,现在它的方式将NULL终止符'\ 0'复制到dinput的第一个元素,这将导致0长度的字符串。

您还需要确保NULL终止dinput。尝试:

for (int i=max-1, n=0; i>=0, n<=max; i--, n++)
    dinput[n] = binput[i];

dinput[max] = '\0';