c++ - Finding matching letters in a string at same spots
问题描述
I need a code to compare two strings: word
and ptw
. Both strings only have one word, and are of equal length and same case. The code needs to check the first character of both words and see if they are same and it will do this untill the end of the word. Then it will output the amount of matching letters (I don't need to know the matching letters).
Example: If word
is windows
and ptw
is winowes
it should output 4
as w
, i
, n
, and s
match.
I have tried the following however it does not check the positions:
string matchingletters(string word, string ptw) {
string result = "";
sort(begin(word), end(word));
sort(begin(ptw), end(ptw));
std::string intersection;
std::set_intersection(begin(word), end(word), begin(ptw), end(ptw),
back_inserter(intersection));
string mlr = to_string(intersection.length());
result = mlr + result;
cout << result << endl;
return result;
}
The result this gives when word
is kanton
and ptw
is balkon
is 4
.
It counts k
even though k
is at 0
position in word and 3
position at ptw and thus they are not in the same postion and should not be counted.
解决方案
假设这两个单词的长度相同,并且由于您不在乎哪些字母匹配,您可以简单地迭代并计算匹配字符
unsigned matchingletters(const std::string& word, const std::string& ptw) {
assert(word.size() == ptw.size());
unsigned count{0};
for (size_t i = 0; i < word.size(); ++i) {
if(word[i] == ptw[i])
count++;
}
return count;
}
推荐阅读
- android - 从 Playstore 下载的测试应用程序中的 android 中资产包的文件访问问题?
- docker - 使用 oozie 调用客户端代码并检索状态
- oracle - 在 oracle 报告执行期间更改当前架构的问题
- python-3.x - Python 3,Argparse。如何检查所需的参数?
- karate - 为什么我们使用 karate-config.js 文件?但我们使用 Java 技术
- json - 参考cpp crow中的json单个对象
- sql - 使用 SQL 比较同一表中的两列和第三列值的大小写
- sql - 如何使用“插入”关键字
- angularjs - 如何使用对 MVC 操作方法的 Angular-js http 调用上传具有多条记录的文件?
- mongodb - 如何将 MongoDB Shell 与外部副本集连接