如何检查字符串是否以C++中的"ed"结尾;

How to check if a string ends with 'ed' in C++;

本文关键字:中的 C++ ed 结尾 是否 何检查 检查 字符串      更新时间:2023-10-16

如何编写一个程序,从用户输入中读取5个字符串,并在C++中只打印那些以字母"ed"结尾的字符串。需要帮助!

解决方案相当简单。

首先,我们定义了一个可以包含5个std::string的容器。为此,我们使用std::vector和构造函数为5个元素保留空间。

然后,我们将控制台中的5个字符串(来自用户输入(复制到向量中。

最后,如果字符串以"ed"结尾,我们将元素从std::vector复制到std::cout

由于程序简单,我无法解释更多。

请看。

#include <iostream>
#include <algorithm>
#include <vector>
#include <string>
#include <iterator>
constexpr size_t NumberOfTexts = 5U;
int main()
{
// Define a container that can hold 5 strings
std::vector<std::string> text(NumberOfTexts);
// Read 5 strings from user
std::copy_n(std::istream_iterator<std::string>(std::cin), NumberOfTexts, text.begin());
// Print the strings with ending "ed" to display
std::copy_if(text.begin(), text.end(), std::ostream_iterator<std::string>(std::cout,"n"), [](const std::string& s){
return s.size()>=2 && s.substr(s.size()-2) == "ed";
});
return 0;
}

简单的解决方案,

#include<iostream>
using namespace std;
bool endsWith(const std::string &mainStr, const std::string &toMatch)
{
if(mainStr.size() >= toMatch.size() &&
mainStr.compare(mainStr.size() - toMatch.size(), toMatch.size(), toMatch) == 0)
return true;
else
return false;
}
int main()
{
string s[5];
for(int i=0;i<5;i++)
{
cin>>s[i];
}
for(int i=0;i<5;i++)
{
if(endsWith(s[i],"ed"))
cout<<s[i]<<endl;
}
}

希望这能有所帮助:(