[英]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;
}
看起來您不清楚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';
希望這能解決。基本上首先檢查單詞的第一個字母和最后一個字母。 如果它們不相等,則它們不是回文。 如果它們相等,則從前端字符和它們各自的后端進行比較。
#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)
回廊
您應該將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';
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.