std::string::compare
是 C++ 标准库 std::string 类的一个成员函数,用于比较两个字符串或部分字符串。compare
方法提供了与字符串比较相关的详细功能,可以直接用来比较字符串的相对顺序。
std::string::compare 方法的声明
int compare(const std::string& str) const noexcept;
int compare(size_t pos1, size_t len1, const std::string& str) const;
int compare(size_t pos1, size_t len1, const std::string& str, size_t pos2, size_t len2) const;
int compare(const char* s) const;
int compare(size_t pos1, size_t len1, const char* s, size_t len2) const;
参数解释
pos1
和len1
:表示要比较的子字符串的起始位置和长度。pos2
和len2
:表示在第二个字符串中的起始位置和长度。- s:C 风格的字符串(
const char*
)。
返回值
- 0:两个字符串相等。
- 负值:调用字符串小于参数字符串。
- 正值:调用字符串大于参数字符串。
- 比较整个字符串
#include <iostream>
#include <string>
int main() {
std::string str1 = "apple";
std::string str2 = "banana";
int result = str1.compare(str2);
if (result == 0) {
std::cout << "str1 is equal to str2" << std::endl;
} else if (result < 0) {
std::cout << "str1 is less than str2" << std::endl;
} else {
std::cout << "str1 is greater than str2" << std::endl;
}
return 0;
}
- 比较部分字符串
#include <iostream>
#include <string>
int main() {
std::string str1 = "apple pie";
std::string str2 = "apple";
// 比较 str1 的前 5 个字符与 str2
int result = str1.compare(0, 5, str2);
if (result == 0) {
std::cout << "The first 5 characters of str1 are equal to str2" << std::endl;
} else if (result < 0) {
std::cout << "The first 5 characters of str1 are less than str2" << std::endl;
} else {
std::cout << "The first 5 characters of str1 are greater than str2" << std::endl;
}
return 0;
}
- 比较
std::string
和 C 风格字符串
#include <iostream>
#include <string>
int main() {
std::string str1 = "hello";
const char* str2 = "hello";
int result = str1.compare(str2);
if (result == 0) {
std::cout << "str1 is equal to str2" << std::endl;
} else if (result < 0) {
std::cout << "str1 is less than str2" << std::endl;
} else {
std::cout << "str1 is greater than str2" << std::endl;
}
return 0;
}
- 比较部分
std::string
和 C 风格字符串
#include <iostream>
#include <string>
int main() {
std::string str1 = "good morning";
const char* str2 = "good";
// 比较 str1 的前 4 个字符与 str2
int result = str1.compare(0, 4, str2, 4);
if (result == 0) {
std::cout << "The first 4 characters of str1 are equal to the first 4 characters of str2" << std::endl;
} else if (result < 0) {
std::cout << "The first 4 characters of str1 are less than str2" << std::endl;
} else {
std::cout << "The first 4 characters of str1 are greater than str2" << std::endl;
}
return 0;
}
解释
str1.compare(str2)
:比较str1
和str2
的整个内容。str1.compare(pos1, len1, str2)
:比较str1
从位置pos1
开始的子字符串(长度为len1
)与str2
。str1.compare(pos1, len1, str2, pos2, len2)
:比较str1
从位置pos1
开始的子字符串(长度为len1
)与str2
从位置pos2
开始的子字符串(长度为len2
)。str1.compare(s)
:比较str1
和 C 风格字符串s
。str1.compare(pos1, len1, s, len2)
:比较str1
从位置pos1
开始的子字符串(长度为len1
)与 C 风格字符串s
的前len2
个字符。