向后阅读时需要检查字符串是否相同

时间:2014-05-21 21:29:18

标签: c++

我不知道这里有什么问题。我虽然是全新的。

#include <iostream>
#include <stdio.h>
#include <string.h>
#include <locale.h>
#include <tchar.h>
#include <string>
using namespace std;


int main()
{
    int string_length;
    string word, wordb;
    cout << "Type in a word\n";
    cin >> word;
    string_length = word.length();
    for (int i=1; i < (string_length+1); i++)
        wordb = wordb + word.at(i);
    if (word == wordb)
        cout << "The word is the same in any direction.\n";
    else 
        cout << "The word is not the same in any direction.\n";
    return 0;
}

很抱歉,如果这很明显。

4 个答案:

答案 0 :(得分:2)

你没有必要&#34;构建&#34;来自wordb的{​​{1}},您可以在一次迭代中逐个直接比较字母:

word

最后,如果单词是真正的回文,你只需要到单词的中间(因为它是对称的)。

答案 1 :(得分:1)

克里斯建议使用std::equal。以下是一个示例:

#include <string>
#include <algorithm>
#include <iostream>

bool is_palindrome(const std::string& s)
{
    return std::equal(s.begin(), s.begin() + s.size()/2, s.rbegin());
}

int main()
{
    std::string word;
    std::cout << "Type in a word\n";
    std::cin >> word;

    if (is_palindrome(word))
        std::cout << "The word is the same in any direction.\n";
    else 
        std::cout << "The word is not the same in any direction.\n";
}

答案 2 :(得分:0)

最简单的方法是写

if ( word == string( word.rbegin(), word.rend() ) )
//...

wordb.assign( word.rbegin(), word.rend() );

if ( word == wordb )
//...

至于你的方法,那么正确的循环将看起来像

for ( string::size_type i = word.length(); i != 0;  )
    wordb.push_back( word[--i];

for ( string::size_type i = word.length(); i != 0;  )
    wordb += word[--i];

答案 3 :(得分:0)

我知道这样做的最简单方法是使用A [DeltaX] == B [-DeltaX]的简单逻辑,而DeltaX <= 1/2长度。 A是你的第一个角色,B是你的最后一个角色,而DeltaX是你的步骤,它不应该超过弦长的1/2(因为你将比较上半场到下半场)。

#include <iostream>
#include <stdio.h>
#include <string.h>
#include <locale.h>
#include <tchar.h>
#include <string>
using namespace std;


int main()
{
int string_length;
int last_character;
bool found_mirror = true;

cout << "Type in a word\n";
cin >> word;

string_length = word.length();
// if the char count is less that 2 than technically it's true
if (string_length < 2)
    return true;

last_character = string_length - 1;
for (int i = 0; i <= (string_length / 2); i++)
{
    if (word[i] != word[last_character - i])
    {
        found_mirror = false;
        break;
    }
}

if (found_mirror)
    cout << "The word is the same in any direction.\n";
else 
    cout << "The word is not the same in any direction.\n";
return 0;
}