# \[mojo-stdlib\] Implement compare operation for String

**URL:** <https://1nfinite.ai/t/mojo-stdlib-implement-compare-operation-for-string/82>\
**Category:** Mojo\
**Created:** [May 16, 2024, 1:13am UTC](https://1nfinite.ai/t/mojo-stdlib-implement-compare-operation-for-string/82 "2024-05-16T01:13:50Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![zhoujing](https://1nfinite.ai/user_avatar/1nfinite.ai/zhoujing/32/16_2.png) [@zhoujing](https://1nfinite.ai/u/zhoujing)\
**Post date:** [May 16, 2024, 1:13am UTC](https://1nfinite.ai/t/mojo-stdlib-implement-compare-operation-for-string/82/1 "2024-05-16T01:13:50Z")

</div>

这是我们在mojo仓库的第二个[PR](https://github.com/modularml/mojo/pull/2378), 实现了`String`的比较大小功能, 比较字符串的大小操作在很多场景都有用, 比如排序, 本次提交耗时比较久, 上游对待PR的态度比较认真, 这个PR也吸引了很多开发者的目光, 给出了很多有用的意见, 以下列出核心功能点:

```auto

@always_inline
fn _str_compare(str1: String, str2: String) -> Int:
    var min_len = len(str1) if len(str1) < len(str2) else len(str2)
    var cmp = memcmp(str1._as_ptr(), str2._as_ptr(), min_len)
    if cmp < 0:
        return -1
    elif cmp > 0:
        return 1
    # now check length for str1 and str2
    if len(str1) == len(str2):
        return 0
    elif len(str1) > len(str2):
        return 1
    else:
        return -1

```

使用memcmp函数进行字符串的比较, 如果`str1 == str2`则返回`0`, 如果`str1 < str2`则返回`-1`, 如果`str1 > str2`则返回`1`
