代码
// ConsoleApplication24.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include <iostream>
#include<string>
using namespace std;
void test1() {
cout << "----基本实验-----\n";
string str1 = "a";
string str2 = "b";
if (0 == str1.compare(str2)) {
cout << "相等" << "\n";
}
else {
cout << "不相等" << "\n";
}
}
//相等和不相等的返回值是什么
void test2() {
cout <<"\n----相等和不相等的返回值是什么-----\n";
string str1 = "ab1";
string str2 = "ab1";
string str3 = "abc";
int n = str1.compare(str2);
cout <<"相等"<<n<< "\n";
n = str1.compare(str3);
cout << "不等" << n << "\n";
}
// 大小字符对返回值的影响
void test3() {
cout << "\n----大小字符对返回值的影响-----\n";
string str1 = "123";
string str2 = "456";
int n = str1.compare(str2);
cout << "123.compare(456)" << n << "\n";
n = str2.compare(str1);
cout << "456.compare(123)" << n << "\n";
}
// 判断不同位置的不同是否对值有影响
// 确认没有影响,都是1和-1,没有更大的数
void test4() {
cout << "\n----判断不同位置的不同是否对值有影响-----\n";
cout << "----确认没有影响,都是1和-1,没有更大的数-----\n";
string str1 = "123";
string str2 = "125";
int n = str1.compare(str2);
cout << "123.compare(125)" << n << "\n";
n = str2.compare(str1);
cout << "125.compare(123)" << n << "\n";
}
int main()
{
test1();
test2();
test3();
test4();
std::cout << "Hello World!\n";
getchar();
}
运行结果