【问题标题】:Strings/words manipulations using std::string::compare (c++)使用 std::string::compare (c++) 进行字符串/单词操作
【发布时间】:2019-08-07 19:33:50
【问题描述】:

问题

我首先将一个字符串分成不同的单词,然后检查是否存在反向单词。我为每个单词制作一个不同的字符串,然后将其反转,然后将其与其他字符串进行比较。

代码

#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

代码没有返回正确的输出。

【问题讨论】:

  • 这按预期工作:ideone.com/9mqB5e 由于您的问题不包含minimal reproducible example 我无法测试您的代码,我只能告诉您它一定有问题。也许您应该使用调试器或打印更多数据。
  • 另外,您的复杂度是 O(N^2),非常糟糕。考虑使用不同的数据结构(如果您有超过 10 个元素)。也许使用std::set&lt;std::string&gt;(总 O(N log N) 和一个好的常数,std::unordered_set&lt;std::string&gt;(总 O(N) 和一个非常差的常数),或者甚至在一个排序的字符串列表中使用二进制搜索(总 O(N log N) 具有非常好的常数)
  • 能否给出完整的代码。当我设置 words = {"hello", "is", "si"}sp_count = words.size() - 1 时,一切都按预期工作。
  • 在您打印单词的循环中,将cout&lt;&lt;words[i]&lt;&lt;endl; 更改为cout &lt;&lt; "'" &lt;&lt; words[i] &lt;&lt; "'" &lt;&lt; endl;,您将看到问题所在。在您打印字符串不相等的输出中也应该很明显。考虑寻找更好的分割字符串的方法,或者如何逐字接受输入。

标签: c++ arrays string function loops


【解决方案1】:

确实,Retired Ninja 是正确的,你在分割个别词的方式上存在问题,尤其是最后一个词。它有一个尾随空格,因此“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 进行比较。

【讨论】:

    猜你喜欢
    • 2017-08-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-04
    • 2019-06-04
    • 1970-01-01
    • 2013-06-20
    • 1970-01-01
    相关资源
    最近更新 更多