C++ std::string 中是否有任何函数可以计算两个字符串的相同起始字符的总数或任何最佳方法
Is there any function in C++ std::string that count total number of same starting characters of two strings or any best way to do
例如。
abcfgf
abdef
ans=2 {"ab" 是一个常见的起始字符}
您可以使用
std::mismatch
,它返回一对迭代器,指示序列开始不同的各个迭代器。
例如,要计算常见前缀的长度,您可以执行以下操作:
#include <iostream>
#include <iterator>
#include <string>
#include <algorithm>
using namespace std;
int main() {
const string l = "abcde", r = "abcdfgh";
cout << distance(begin(l), mismatch(begin(l), end(l), begin(r)).first) << endl;
}
似乎有一个内置函数可以做到这一点,如这个答案所示。
但是,您可以通过简单地使用循环(如果需要,但不建议它(来做到这一点,如下所示:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str1 = "abcfgf";
string str2 = "abdet";
int counter = 0;
for(int i = 0; i < str1.size() && i < str2.size(); ++i)
if(str1[i] == str2[i])
counter++;
cout << counter << endl;
return 0;
}
输出:
阿拉伯数字
相关文章:
- 当可输入框在窗口中处于活动状态时获得通知的任何方法
- 无法"this"指针传递到另一个类并在 CPP 中调用该类的任何方法
- 任何方法都可以在C++中比较数据结构中的许多方法
- 在DelphiInterface上实现Dynamic_cast以获取基础对象类的任何方法
- 使用原始字节向量作为提升序列化的存档的任何方法
- 当我的结构中的任何变量发生更改时触发的事件的任何方法
- 是否有任何方法可以将两个boost :: multipRecision :: cpp_int编号乘以
- 是否有任何方法可以通过使用声明来提高可见度
- 设置用G 构建的二进制版本的任何方法
- 在参数相关查找之前进行模板替换的任何方法(或解决方法?
- 是否有任何方法可以在用户输入文本时读取字符
- 识别哪种QTIMER的任何方法
- C 模板功能是否有任何方法可以采用n个参数
- 告诉链接器"respect" __attribute__((__used__))的任何方法
- 是否有任何方法可以在初始化之前更改变量的类型,您可以用示例解释
- 是在32位系统上为Android Studio安装CMAKE的任何方法,以允许C 支持
- Winforms-将Visual C 项目UI转换为Visual C#的任何方法
- 复制列表类的构造函数,而无需在实现中使用任何方法
- 在成员变量上执行std :: upper_bound的任何方法
- 在海湾合作委员会中加快宏观预处理的任何方法