C风格字符串比较strcmp和string类字符串比较

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;
}

执行结果:

  • 11
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

WendyWJGu

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值