条件表达式如何比较字符串? [英] How does conditional expression compare strings?

查看:139
本文介绍了条件表达式如何比较字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#!/usr/bin/env bash
echo 'Using conditional expression:'
[[ ' ' < '0' ]] && echo ok || echo not ok
[[ ' a' < '0a' ]] && echo ok || echo not ok
echo 'Using test:'
[ ' ' \< '0' ] && echo ok || echo not ok
[ ' a' \< '0a' ] && echo ok || echo not ok

输出为:

Using conditional expression:
ok
not ok
Using test:
ok
ok

bash --version:GNU bash, version 4.2.45(1)-release (x86_64-pc-linux-gnu)

uname -a:Linux linuxmint 3.8.0-19-generic

推荐答案

打击手册说:

当与[[一起使用时,<和>运算符使用当前语言环境按字典顺序排序.测试命令使用ASCII排序.

When used with [[, the < and > operators sort lexicographically using the current locale. The test command sorts using ASCII ordering.

这归结为分别使用strcoll(3)或strcmp(3).

This boils down to using strcoll(3) or strcmp(3) respectively.

使用以下程序(strcoll_strcmp.c)进行测试:

Use the following program (strcoll_strcmp.c) to test this:

#include <stdio.h>
#include <string.h>
#include <locale.h>

int main(int argc, char **argv)
{
    setlocale(LC_ALL, "");

    if (argc != 3) {
        fprintf(stderr, "Usage: %s str1 str2\n", argv[0]);
        return 1;
    }

    printf("strcoll('%s', '%s'): %d\n",
           argv[1], argv[2], strcoll(argv[1], argv[2]));
    printf("strcmp('%s', '%s'): %d\n",
           argv[1], argv[2], strcmp(argv[1], argv[2]));

    return 0;
}

请注意区别:

$ LC_ALL=C ./strcoll_strcmp ' a' '0a'
strcoll(' a', '0a'): -16
strcmp(' a', '0a'): -16

$ LC_ALL=en_US.UTF-8 ./strcoll_strcmp ' a' '0a'
strcoll(' a', '0a'): 10
strcmp(' a', '0a'): -16

我不确定为什么要比较这些.这一定是由于某些英语词典编目规则所致.我认为 ISO 14651比较字符串和通用模板描述的方法中描述了确切的规则可定制的订单和随附的模板表. Glibc将此数据包含在libc/localedata/locales下的源树中.

Exactly why these compare as such I'm not sure. This must be due to some English lexicographical sorting rules. I think the exact rules are described in ISO 14651 Method for comparing character strings and description of the common template tailorable ordering and the accompanying template table. Glibc contains this data in the source tree under libc/localedata/locales.

这篇关于条件表达式如何比较字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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