[英]Strings/words manipulations using std::string::compare (c++)
我首先將一個字符串分成不同的單詞,然后檢查一個單詞的反向是否存在。 我正在為每個單詞制作一個不同的字符串,然后將其反轉並將其與其他字符串進行比較。
#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!='\0')
{
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!='\0')
{
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
該代碼沒有返回正確的輸出。
確實,退休忍者是正確的,你在切割獨立單詞的方式上有問題,尤其是最后一個單詞。 它有一個尾隨空格,所以當然“si”和“si”不相等。
在 while 塊中嘗試以下更改:
while ((ch = str[i]) != '\0') {
// 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
進行比較。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.