比较字符串大小

1、打基础的源码:

题目来源:牛客网


int mystrcmp(const char* src, const char* dst) {

    // write your code here......
    //确定长度 分为三种情况进行比较
    while ( *src != '\0' && *dst != '\0') {
        if (*src > *dst) {
            return 1;
        } else if ( *src < *dst) {
            return -1;
        } else {  //这里处理的是关键
            src++;
            dst++;
        }

    }
    if ( *src != '\0' && *dst == '\0') {
        return 1;
    }
    if ( *src == '\0' && *dst != '\0') {
        return -1;
    }
    return 0; //这里也是关键,和上面的else呼应
}

原始的出错代码,易错分析:

int mystrcmp(const char* src, const char* dst) {

    // write your code here......
    //确定长度 分为三种情况进行比较
    while ( *src != '\0' && *dst != '\0') {
        if (*src > *dst) {
            return 1;
        } else if ( *src < *dst) {
            return -1;
        } else ( *src ==*dst) {  //这里处理易错
            return 0; //这里不应该是返回0,而是应该放在末尾
        }
        src++;
        dst++;

    }
    // 这判断,其实使用if就可以,while有点多此一举
    while ( *src != '\0' && *dst == '\0') {
        return 1;
    }
    while ( *src == '\0' && *dst != '\0') {
        return -1;
    }
    return 0; // 如果只在循环里有返回,这里没有返回,就会报错
}

2、STL升级版

1)直接调用函数进行比较两个字符串

  • 字符串比较是按字符的ASCII码进行对比
    = 返回 0
    > 返回 1
    < 返回 -1
#include<string>  头文件
string s1 = "11111";
string s2 = "22222";
int c = s1.compare(s2); //  c 是多少呢? -- -1

测试代码:

#include<iostream>
#include<string>
using namespace std;
//字符串比较
void test01()
{

	string s1 = "hello";
	string s2 = "aello";

	int ret = s1.compare(s2);

	if (ret == 0) {
		cout << ret << endl;
		cout << "s1 等于 s2" << endl;
	}
	else if (ret > 0)
	{
		cout << ret << endl;
		cout << "s1 大于 s2" << endl;
	}
	else
	{
		cout << ret << endl;
		cout << "s1 小于 s2" << endl;
	}

}

int main() {

	test01();

	system("pause");

	return 0;
}

运行结果:

1
s1 大于 s2

2)s1 == s2也是ok 的

3、strcmp(s1,s2) ok吗?

针对 string 类型的变量是不可以的
strcmp函数要求的形参需要是char [] 类型的数据。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值