在 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;
}
根據具體需求選擇合適的方法來處理字符串長度不一致的情況。