如何将一个单词拆分成字母,并将它们放入一个无序的列表/集合中

How to split a word into letters and put them into an unordered list/set?

本文关键字:一个 无序 集合 列表 拆分 单词      更新时间:2023-10-16

我正在尝试构建一个简单的变位符检查器,用于比较两个用户输入并打印这两个输入是否为变位符。

我认为这将是一个很好的方法:

-要求用户输入1和用户输入2

-将input1和input2拆分为单个字母

-将input1个字母放入一个无序集,将input2个字母放入另一个无序集中。

-if (unordered set 1 == unordered set 2)这对是一个变位词。

我很难弄清楚如何将输入拆分为单独的字母,并将每个字母放入自己的无序列表/集合中。

#include <iostream>
int main()
{
std::cout << "Hey there! enter a pair of words and tell you if they're an anagram or not." << endl;
std::cout << "Enter first word: ";  
std::string firstword{};
std::cin >> firstword;
std::cout << "Enter second word: ";
std::string secondword{};
std::cin >> secondword;
//split firstword into letters
//put letters into set1
//split secondword into letters
//put letters into set2
//if (set1 == set2)
//the pair is an anagram
return 0;
}

有几种方法可以做到这一点。我选择的方法是首先对每个字符串进行排序,遍历每个字符串,并将一个字符串的索引与另一个字符串索引进行比较。在C++中,每个字符串都由字符或字符组成,因此您可以通过它们的索引访问字符串的各个部分。

#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
string firstWord;
string secondWord;
bool isAnagram;
cout << "Hello! Enter the first word: ";
cin >> firstWord;
sort(firstWord.begin(), firstWord.end());
cout << "Enter the second word: ";
cin >> secondWord;
sort(secondWord.begin(), secondWord.end());
if(firstWord.length() == secondWord.length())
{
for(int i = 0; i < firstWord.length(); i++)
{
if(firstWord[i] == secondWord[i])
{
isAnagram = true;
}
else
{
isAnagram = false;
break;
}
}
}
else
{
isAnagram = false;
}
if(isAnagram)
{
cout << "It's an anagram!n";
}
else
{
cout << "It's not an anagram.n";
}
return 0;
}

一些附带说明:我包含了使用命名空间std的在我的程序顶部。这通常被认为是一种糟糕的做法,因为它将整个std命名空间拉入全局命名空间,并可能导致名称冲突。但是,它可以很好地用于测试目的。我还包含了算法预处理器指令,其中包含用于对字符串排序的sort((函数。

如果给定的单词是变位词,那么它们必须是同一字母集的排列。

#include <algorithm>
bool are_anagrams(const std::string& lhs, const std::string& rhs)
{
if (lhs.size() != rhs.size())
{
return false;
}
return std::is_permutation(lhs.cbegin(), lhs.cend(), rhs.cbegin());
}

std::is_permutation是<algorithm>标头中的一个免费函数,用于检查所提供的迭代器是否指向同一集合的排列。

参考"如何将字符串拆分为字母并放入集合"的问题,可以使用std::set构造函数来实现这一目标。

std::string word = "foo";
auto start = word.cbegin();
auto end = word.cend();
std::set<char> letters{start, end};

std::set构造函数将一对迭代器作为参数,并使用它们来构造对象。

您可以像迭代向量一样迭代字符串。元素只是字母(如char(。