如何将一个单词拆分成字母,并将它们放入一个无序的列表/集合中
How to split a word into letters and put them into an unordered list/set?
我正在尝试构建一个简单的变位符检查器,用于比较两个用户输入并打印这两个输入是否为变位符。
我认为这将是一个很好的方法:
-要求用户输入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(。
相关文章:
- 如何将一个单词拆分成字母,并将它们放入一个无序的列表/集合中
- 仅从无序集合中删除一个项目
- 将一个向量对放在一个无序映射与一个映射中
- 如何从一个无序集合中获取一个元素
- 以std::字符串作为关键字,按字典顺序对一个无序映射进行排序
- 使用shared_ptr<字符串>转换为一个无序集合<字符串>
- 如何使用一个整数数组作为一个无序映射的键
- C++将一个值存储在无序对中
- 对一个无序映射c++进行排序时数据丢失
- 如何在一个无序映射中存储2个以上的变量
- 声明一个无符号int和一个数组的无序映射(将具有不同的大小)
- 判断一个键是否在一个c++无序映射中最省时的方法是什么
- 插入到一个无序映射的无序映射中
- 将向量排序到一个无序映射c++11中
- 如何使用C++(g++编译器)初始化一个无序集
- 包含一个图形节点作为关键字的无序映射
- 如何在C++中迭代一个无序的集合
- 为什么我可以在一个文件中无序地初始化两个静态类变量,而不能初始化三个
- 填充一个无序的vector元素指针队列
- 使用自定义哈希函数插入到一个无序集合中