问题
我首先将字符串分为不同的单词,然后检查是否存在单词的反面是否存在。我正在为每个单词制作一个不同的字符串,然后将其反转,然后将其与其他字符串进行比较。
代码
#include<bits/stdc++.h>
using namespace std;
int main()
{
string str;
getline(cin,str);
cout<<"the string inputted is "<<str;
char ch=str[0];
int i=0;
int sp_count=0;
while(ch!=' ')
{
ch=str[i];
if(ch==' ')
{
sp_count++;
}
i++;
}
string words[sp_count+1];
ch=str[0];
i=0;
int w=0,it=0;
while(ch!=' ')
{
ch=str[i];
if(ch==' ')
{
w++;
i++;
continue;
}
words[w]=words[w]+ch;
i++;
}
for(int i=0;i<sp_count+1;i++)
{
cout<<words[i]<<endl;
}
for(int i=0;i<sp_count+1;i++)
{ string temp=words[i];
reverse(temp.begin(),temp.end());
for(int j=i+1;j<sp_count+1;j++)
{ int x=10;
x=temp.compare(words[j]);
if(x==0)
{
cout<<"strings "<<temp << " and "<<words[j]<<" are equal"<<endl;
}
else
{
cout<<"strings "<<temp << " and "<<words[j]<<" are not equal"<<endl;
}
}
}
return 0;
}
当我输入字符串时:
Hello is si
输出是:
strings olleh and is are not equal
strings olleh and si are not equal
strings si and si are not equal
代码不返回正确的输出。
的确,退休的忍者是正确的,您在切除in亵词的方式上有一个问题,尤其是最后一个单词。它有一个尾随的空白,所以当然是" si"one_answers" si"不等。
尝试以下更改段:
while ((ch = str[i]) != ' ') {
// ch = str[i];
if (ch == ' ') {
w++;
i++;
continue;
}
words[w] = words[w] + ch;
i++;
}
我将获得以下输出:
strings olleh and is are not equal
strings olleh and si are not equal
strings si and si are equal
您正在增加i
,而不是更新ch
,而是在比较旧的ch
值与0
。