回文 C++ (strcpy)

Palindrome C++ (strcpy)

我试图在互联网上找到解决方案,但找不到与此类似的解决方案。我正在使用 strcpy 和迭代在 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;
}

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

您还需要确保以 NULL 终止输入。尝试:

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

dinput[max] = '[=10=]';

看来您不清楚 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] = '[=12=]';

更新,回应OP的评论

你需要:

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

希望这个solves.Basically首先只检查单词的第一个字母和最后一个字母。如果它们不相等,则它们不是回文。如果它们相等,则继续从前端字符与它们各自的后端进行比较。

#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;
}
if(strcmp(word,strrev(word)==0)

回文