[英]how to check if 2 strings contain equal characters?
im trying to make a function that will take two strings from user and check if they contain equal characters.我正在尝试创建一个函数,该函数将从用户那里获取两个字符串并检查它们是否包含相等的字符。 For example test and set , both these strings contain the letter t and s so the output should be
true
.例如 test 和 set ,这两个字符串都包含字母 t 和 s 所以输出应该是
true
。 I started a few weeks ago so im having some trouble with executing the code correctly.我几周前就开始了,所以我在正确执行代码时遇到了一些麻烦。 Can someone please explain what im doing wrong?
有人可以解释一下我做错了什么吗? thanks everyone
谢谢大家
#include <iostream>
#include <string>
bool equal(char first, char second);
using namespace std;
int main() {
string first;
string second;
bool equal;
int se;
cout << "enter a string " << endl;
getline(cin, first);
cout << "enter another string " << endl;
getline(cin, second);
equal(first ,second);
if (equal) {
cout << "strings are equal" << endl;
} else if (!equal) {
cout << "strings not " << endl;
}
return 0;
}
bool equal(string first, string second) {
for (int i = 0; i < first.length(); i++) {
for (int j = j + 1; i < second.length(); i++) {
if (i == j)
return true;
else
return false;
}
}
}
You may use您可以使用
bool contain_same_letters(const std::string& lhs, const std::string& rhs)
{
return std::set<char>(lhs.begin(), lhs.end())
== std::set<char>(rhs.begin(), rhs.end());
}
The inner loop of equal()
is wrong, it should be: equal()
的内循环是错误的,应该是:
for (int j = 0; j < second.size(); j++)
if (first[i] == second[j])
instead of代替
for (int j = j + 1; i < second.length(); i++) {
if (i == j)
We can guess at the error message (don't make us, though!).我们可以猜测错误信息(但不要逼我们!)。 You declared
bool equal(char first, char second);
你声明
bool equal(char first, char second);
but defined bool equal(string first, string second)
.但定义
bool equal(string first, string second)
。 Hence, when you try to call it, the compiler complains about an incorrect argument type.因此,当您尝试调用它时,编译器会抱怨参数类型不正确。
Your next problem will be at runtime, because your implementation of equal
isn't working right.您的下一个问题将出现在运行时,因为您对
equal
的实现无法正常工作。 But this is an algorithm problem;但这是一个算法问题; you should think about how it should work.
你应该考虑它应该如何工作。 You can't return when there's one match, but you can return when there's one mis-match.
一场比赛你不能回来,但一场错配你可以回来。
There is also a smart trick by using the functions from <algorithm>
but I won't give that away.使用
<algorithm>
的函数还有一个聪明的技巧,但我不会放弃。 One hint, though: it's hard to compare "test" and "set" because the letters are in a different order.不过,有一个提示:很难比较“test”和“set”,因为字母的顺序不同。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.