使用std :: string ::比较(C )的字符串/单词操纵
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!=' ')
{
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"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
。
相关文章:
- 从字符串变量中逐字符读取单词
- 使用std::mt19937从字符串中返回一个随机单词
- C++-字符串是否包含一个带有简单循环的单词
- 在C++中查找(奇怪的)字符串中的单词
- 当字符串是某个单词时给出输出?
- 替换字符串中的单词,但忽略引号中的单词
- 替换字符串位置 X 中的单词C++
- 视觉C++使用 map 来比较字符串中的每个单词
- 给定一个单词数组和一个字符串,如何计算给定字符串中的所有单词
- 输出返回编号。等于输入字符串的单词的字符串数
- 在字符串的每个单词的末尾插入字符串
- 分析字符串中的双精度和单词
- 如何使用运算符>>在自定义字符串中输入多个单词?
- 反转字符串中单词的位置,而不更改 O(1) 空格限制中特殊字符的顺序
- 使用正则表达式c++从单词和分隔符之间的字符串中提取所有子字符串
- C++读取大文件并将其保存到字符串中,然后删除特定的随机单词
- 字符串单词的唯一哈希值
- 使用std :: string ::比较(C )的字符串/单词操纵
- 如何比较字符串单词和聊天猜测
- 用C++计算文本文件中的相同字符串/单词