在 C++ 中,处理字符串长度不一致的情况有多种方法。以下是一些建议:
std::string
类的成员函数 size()
和 length()
获取字符串长度。std::string str1 = "Hello";
std::string str2 = "World!";
if (str1.size() != str2.size()) {
std::cout << "Strings have different lengths!" << std::endl;
}
std::mismatch()
函数查找两个字符串中第一个不匹配的字符。#include <algorithm>
#include <iostream>
#include <string>
int main() {
std::string str1 = "Hello";
std::string str2 = "World!";
auto result = std::mismatch(str1.begin(), str1.end(), str2.begin());
if (result.first != str1.end()) {
std::cout << "The first mismatched character is at position " << std::distance(str1.begin(), result.first)
<< " in the first string and position " << std::distance(str2.begin(), result.second)
<< " in the second string." << std::endl;
} else {
std::cout << "The strings are identical." << std::endl;
}
return 0;
}
std::substr()
函数获取子串,然后进行比较。#include <iostream>
#include <string>
int main() {
std::string str1 = "Hello";
std::string str2 = "World!";
size_t min_length = std::min(str1.length(), str2.length());
for (size_t i = 0; i < min_length; ++i) {
if (str1[i] != str2[i]) {
std::cout << "The strings differ at position "<< i << ": " << str1[i] << " vs " << str2[i] << std::endl;
break;
}
}
if (str1.length() != str2.length()) {
std::cout << "The strings have different lengths!" << std::endl;
}
return 0;
}
根据具体需求选择合适的方法来处理字符串长度不一致的情况。