题解 | 比较字符串大小

比较字符串大小

https://www.nowcoder.com/practice/963e455fdf7c4a4a997160abedc1951b

#include <iostream>
using namespace std;

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

int main() {

    char s1[100] = { 0 };
    char s2[100] = { 0 };

    cin.getline(s1, sizeof(s1));
    cin.getline(s2, sizeof(s2));

    int ret = mystrcmp(s1, s2);

    cout << ret << endl;

    return 0;
}

int mystrcmp(const char* src, const char* dst) {
    int src_count = 0, dst_count = 0, result = 0;
    // write your code here......
    
    while(*src != '\0' && *dst != '\0'){
        if(*src == *dst){
            src++;
            dst++;
        }else if(*src > *dst){
            return 1;
        }else if(*src < *dst){
            return -1;
        }
    }
    if(*src != '\0' && *dst == '\0'){
        return 1;
    }
    if(*src == '\0' && *dst != '\0'){
        return -1;
    }
    return 0;

}

比较两个字符串的大小主要看两个优先级

✅ 优先级 1:第一个不同的字符 决定最终结果(ASCII 值大的字符串更大);

✅ 优先级 2:只有当所有对应字符都相同时,才用 “长度” 判断(更长的字符串更大)。

C/C++题解 文章被收录于专栏

记录个人编程题的解题思路以及学习的新知识

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务