在 C++ 中找到一个字符串是否以另一个给定字符串开头和结尾


在该问题中,我们得到了两个字符串 str 和 corStr。我们的任务是找到一个字符串是否以另一个给定字符串开头和结尾。 

我们举个例子来理解该问题,

输入: str = “abcprogrammingabc” conStr = “abc”

输出: 

解决方法: 

要解决该问题,我们需要检查字符串是否以 corStr 开头和结尾。为此,我们将找到字符串和 corStr 的长度。然后,我们将检查 len(字符串) > len(corStr),如果否,则返回假。
检查大小为 corStr 的前缀和后缀是否相等,并检查它们是否包含 corStr。

为了说明我们解决方案的工作原理,这里提供一个程序,

Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

示例

动态演示

#include <bits/stdc++.h>
using namespace std;

bool isPrefSuffPresent(string str, string conStr) {
   
   int size = str.length();
   int consSize = conStr.length();
   if (size < consSize)
   return false;
   return (str.substr(0, consSize).compare(conStr) == 0 && str.substr(size-consSize, consSize).compare(conStr) == 0);
}

int main() {
   
   string str = "abcProgrammingabc";
   string conStr = "abc";
   if (isPrefSuffPresent(str, conStr))
      cout<<"The string starts and ends with another string";
   else
      cout<<"The string does not starts and ends with another string";
   return 0;
}

输出 −

The string starts and ends with another string

更新于: 22-Jan-2021

496 次查看

开启你的 职业Careers

通过完成课程获得认证

入门
广告