C++ 相当于 Java StringUtils.indexOfDifference
C++ equivalent of Java StringUtils.indexOfDifference
对于 C++20,是否有与 Java 的 StringUtils.indexOfDifference()
等效的库?
比较两个大字符串并确定它们不同之处的有效方法是什么?
您可以使用 <algorithm>
中的 std::mismatch
Returns the first mismatching pair of elements from two ranges
例如
#include <algorithm>
#include <iostream>
#include <iterator>
#include <string>
std::size_t IndexOfDifference(std::string const& lhs, std::string const& rhs) {
auto diff = std::mismatch(lhs.begin(), lhs.end(), rhs.begin());
return std::distance(lhs.begin(), diff.first);
}
int main() {
std::cout << IndexOfDifference("foobar", "foocar");
}
3
如果您注意导致结果中出现结束迭代器的不同情况,则可以使用 std::mismatch
:
#include <algorithm>
#include <string>
#include <iterator>
#include <iostream>
void mism(const std::string& a, const std::string& b){
auto its = std::mismatch(a.begin(), std::next(a.begin(),std::min(a.size(),b.size())),b.begin());
if (its.first == a.end() && its.second == b.end()) {
std::cout << "the strings are equal\n";
} else if (its.first != a.end() && its.second != b.end()){
std::cout << "the strings differ at " << *(its.first) << " and " << *(its.second) << "\n";
} else if (its.first == a.end()) {
std::cout << "the second string starts with the first\n";
} else if (its.second == b.end()) {
std::cout << "the first string start with the second\n";
}
}
int main() {
mism("foo1abc","foo2abc");
mism("foo","foo");
mism("foo123","foo");
mism("foo","foo123");
}
对于 C++20,是否有与 Java 的 StringUtils.indexOfDifference()
等效的库?
比较两个大字符串并确定它们不同之处的有效方法是什么?
您可以使用 <algorithm>
std::mismatch
Returns the first mismatching pair of elements from two ranges
例如
#include <algorithm>
#include <iostream>
#include <iterator>
#include <string>
std::size_t IndexOfDifference(std::string const& lhs, std::string const& rhs) {
auto diff = std::mismatch(lhs.begin(), lhs.end(), rhs.begin());
return std::distance(lhs.begin(), diff.first);
}
int main() {
std::cout << IndexOfDifference("foobar", "foocar");
}
3
如果您注意导致结果中出现结束迭代器的不同情况,则可以使用 std::mismatch
:
#include <algorithm>
#include <string>
#include <iterator>
#include <iostream>
void mism(const std::string& a, const std::string& b){
auto its = std::mismatch(a.begin(), std::next(a.begin(),std::min(a.size(),b.size())),b.begin());
if (its.first == a.end() && its.second == b.end()) {
std::cout << "the strings are equal\n";
} else if (its.first != a.end() && its.second != b.end()){
std::cout << "the strings differ at " << *(its.first) << " and " << *(its.second) << "\n";
} else if (its.first == a.end()) {
std::cout << "the second string starts with the first\n";
} else if (its.second == b.end()) {
std::cout << "the first string start with the second\n";
}
}
int main() {
mism("foo1abc","foo2abc");
mism("foo","foo");
mism("foo123","foo");
mism("foo","foo123");
}