1. 在C语言中,不能直接用等号来比较字符串,因为字符串的名字是地址,而且引号包含起来的字符串也表示的是地址.
比如: char InputName = {"lisan"};
char ManageName = {"lisan"};
当我们需要判断输入的用户名是不是管理员的时候,他们来自两个不同的地方,存储的地址肯定是不一样的,而存储姓名的内容确实相同的,比较地址得到的是不相等。那么比较地址就达不到我们比较的目的。所以要通过比较字符串内容来判断两个字符串是否匹配。我们使用strcmp()比较字符串内容。
int strcmp(string1,string2)
返回一个整数值,指示字符串之间的关系:
<0 - 第一个不匹配的字符在 string1 中的值小于 string2 中的值
=0 - 两个字符串的内容相同
>0 - 第一个不匹配的字符在 string1 中的值大于 string2 中的值
程序源码:
// Len_compare.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <string>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
// 字符串完全匹配, 返回0
int cmpResult = strcmp("ABC", "ABC" );
printf("\n\t1. cmpResult = %d\n", cmpResult);
// 第一个不匹配的字符在参数1中的值大于参数2 中的值
cmpResult = strcmp("abc", "ABC");
printf("\n\t2. cmpResult = %d\n", cmpResult);
// 第一个不匹配的字符在参数1中的值小于参数2 中的值
cmpResult = strcmp("ABC", "abc" );
printf("\n\t3. cmpResult = %d\n", cmpResult);
// 第一个不匹配的字符在参数1中的值大于参数2 中的值
cmpResult = strcmp("abcde", "abc");
printf("\n\t4. cmpResult = %d\n", cmpResult);
// 字符数组的长度不一样,但是存储的内容是一样的
// 比较得到的结果也是相等的, 返回0
char word1[7] = { "abcdef" };
char word2[10] = { "abcdef" };
cmpResult = strcmp(word1, word2);
printf("\n\t5. cmpResult = %d\n", cmpResult);
return 0;
}
执行结果:
2. 比较string类字符串
string类字符串,因为类设计中做了函数重载,重新定义了运算符,所以可以使用string对象而不是char数组。同样也可以调用string类中的compare函数实现两个字符串的比较。
源码:
// Len_compare.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <string>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
string word = "?C++";
for (char i = 'A'; i < 'Z'; i++)
{
word[0] = i;
if (word != "VC++")
{
printf("\n\t error %s", word.c_str());
}
else
{
printf("\n\t\t correct %s", word.c_str());
}
}
string word1 = "Visual Studio 2013";
string word2 = "Visual Studio 2013";
int nResult = word1.compare(word2);
printf("\n\n\t1. 比较的结果是: %d", nResult);
word1 = "Visual Studio 2013";
word2 = "Visual Studio 2015";
nResult = word1.compare(word2);
printf("\n\n\t2. 比较的结果是: %d", nResult);
return 0;
}
执行结果: