我想检查字符串向量中的所有单词是否等于一个单独的字符串。假设我有向量vector<string> words = { "birds", "flies", "but", "fish", "swim" };
,我想检查所有这些元素是否等于带有for循环的字符串。
for (int i = 0; i < words.size(); ++i) {
cout << words[i];
if (words[i] == "birdsfliesbutfishswim") {
sentenceCorrect = true;
}
}
现在,代码将打印出words[i]
为“ birdsfliesbutfishswim ”,但它不会与for循环中的字符串相等。虽然,for循环中的字符串也是“ birdsfliesbutfishswim ”。这是为什么?为什么我不能将words[i]
与字符串进行比较,如上例所示?什么会使它发挥作用?
答案 0 :(得分:1)
如果要检查所有字符串是否等于字符串,请使用以下命令:
string totalWord;
for (const auto& word : words)
{
totalWord += word;
}
这将所有字符串组合成一个字符串。您甚至可以使用std::accumulate
执行此操作:
string totalWord = std::accumulate(words.begin(), words.end(), std::string{});
在此之后,只需检查新字符串是否等于您要检查的内容:
if (totalWord == "birdsfliesbutfishswim")
{
sentenceCorrect = true;
}
答案 1 :(得分:0)
如果你想将“birdsfliesbutfishswim”与向量组合中的所有字符串进行比较,你实际上需要将它们组合起来。你不需要自己编写循环,但你可以使用算法来做到这一点:
#include <vector>
#include <numeric>
#include <string>
#include <iostream>
int main() {
std::vector<std::string> words = { "birds", "flies", "but", "fish", "swim" };
std::string sentence = std::accumulate(words.begin(),words.end(),std::string());
if (sentence == "birdsfliesbutfishswim") std::cout << "dogscanswimtoo\n";
return 0;
}
答案 2 :(得分:0)
没有构建新字符串的好方法。
#include<vector>
#include<string>
#include <iostream>
bool isSentenceCorrect(const char* sentence, const std::vector<std::string>& words) {
for(const auto& word : words){
auto word_size = word.size();
if(word.compare(0, word_size, sentence, word_size) != 0) {
return false;
}
sentence += word_size;
}
return *sentence == '\0';
}
int main() {
std::vector<std::string> words = {"birds", "flies", "but", "fish", "swim"};
std::cout << std::boolalpha << isSentenceCorrect("birdsfliesbutfishswim", words);
return 0;
}