我寫了一個迴文檢查函數,它在大多數情況下都能正常工作,但是如果空格或標點符號不在字符串的中間,它就表示它不是迴文。如何忽略空白和標點符號?
即
初試:
Enter string to test for palindrome:
hannah
string is a palindrome.
二測:
Enter string to test for palindrome:
han nah
string is a palindrome.
第三次試驗:
Enter string to test for palindrome:
hann.ah
string is not a palindrome.
第四個測試:
Enter string to test for palindrome:
han.nah
string is a palindrome.
我想知道如果有一種方法可以忽略空格和標點符號都在一起,這樣h.annah
或hann ah
會被認爲是迴文?
這裏是我的代碼:
void isPalindrome (string s){
if(equal(s.begin(), s.begin() + s.size()/2, s.rbegin()))
cout << "string is a palindrome. " << endl;
else
cout << "string is not a palindrome. " << endl;
}
int main(){
string test1;
cout << "Enter string to test for palindrome: " << endl;
getline(cin, test1);
isPalindrome(test1);
string test2;
cout << "Enter string to test for palindrome: " << endl;
getline(cin, test2);
isPalindrome(test2);
string test3;
cout << "Enter string to test for palindrome: " << endl;
getline(cin, test3);
isPalindrome(test3);
return 0;
}
你應該在編寫函數的習慣得到像'isPalindrome'這樣的返回'bool'的方式,不是產生輸出的方式,也沒有給出其實際做法的其他指示。另外,像這樣的參數應該是'const string&s'來避免繁瑣的副本,並允許編譯器更好地優化。 – tadman
您還需要做一些基本的閱讀,瞭解如何在程序變成無盡的剪切和粘貼痛苦之前編寫一個簡單的'for'循環。編寫一個循環執行三次應該很簡單,並且比你在這裏更簡潔。 – tadman