c++ - 关于strcmp()的一种实现算法的疑问

查看:194
本文介绍了c++ - 关于strcmp()的一种实现算法的疑问的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

在《See MIPS Run》的Chapter 9 Reading MIPS Assembly Language中,提到到这样一段代码:

We’ll use the same example as in Chapter 8: an implementation of the C library function strcmp(). But this time we’ll include essential elements of assembly syntax and also show some hand-optimized and -scheduled code. The algorithm shown is somewhat cleverer than a naïve strcmp() function; we’ll start with this code—still in C—in a form that has all the operations separated out to make them easier to play with, as follows:

int strcmp (char *a0, char *a1)
{
    char t0, t1;
    while (1) {
        t0 = a0[0];
        a0 += 1;
        t1 = a1[0];
        a1 += 1;
        if (t0 == 0)
            break;
        if (t0 != t1)
            break;
    }
    return (t0 - t1);
}

图片版的原文在此:

不是很懂 t0 = a0[0];t1 = a1[0];这个为什么放在while循环里。。。这样难道不是每次循环都从首字符开始了么。。。那么怎么完成字符串的比较呢?

还要一个疑问是。。。if (t0 == 0)难道不应该是if (t0 =='\0')么。。。

解决方案

1、你别忘了还有 a0 += 1;a1 += 1;,这样其地址会根据数组的类型向后步进,每次步进后 a0[0]a1[0] 取到的值也会跟着步进地址中的值而变化。另外,这个实现可以更简单。

int myStrcmp(const char* dest, const char* src)
{
    // 循环条件每个字符都相等
    // 并且两个字符串都没有到结尾
    // 一旦以上某个条件不满足则跳出while
    while (*dest == *src && *dest != '\0' && *src != '\0')
    {
        dest++; src++;
    }
    // 此时计算最后指向的两个字符的差值,返回对应值即可
    return *dest > *src ? 1 : (*dest == *src ? 0 : -1);
}

2、if (t0 == 0) 在 ASCII 码表中,char '\0' 就是十进制的 0。

这篇关于c++ - 关于strcmp()的一种实现算法的疑问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆