字符串比较和单个字符的字母顺序 [英] String Comparison And Alphabetic Order of Individual Characters

查看:41
本文介绍了字符串比较和单个字符的字母顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个关于字符串比较与字符比较的问题.

字符>0(零)相应地具有以下十进制值6248.>

当我比较以下代码中的两个字符时,我得到值 True(这是正确的)

Console.WriteLine('>' > '0');

当我比较以下代码中的两个单字符字符串时,我得到值 -1 表示 ">" 小于0"(默认文化是英文)

Console.WriteLine(string.Compare(">", "0"));

而在以下代码中比较3"和1"(5149 代码值)返回 1(如预期的那样))

Console.WriteLine(string.Compare("3", "1"));

另外,string.Compare(string str1, string str2) 文档说:

<块引用>

比较使用当前文化来获取特定于文化的大小写规则和字母顺序等信息个别字符

您能否解释(或提供一些文档的参考)字符串比较是如何实现的,例如如何计算单个字符的字母顺序等?

解决方案

当你比较字符'>''0'时,你是在比较它们的序数值.

要从字符串比较中获得相同的行为,请提供序数字符串比较类型:

 Console.WriteLine(string.Compare(">", "0", StringComparison.Ordinal));Console.WriteLine(string.Compare(">", "0", StringComparison.InvariantCulture));Console.WriteLine(string.Compare(">", "0", StringComparison.CurrentCulture));

默认使用当前区域性,其排序顺序旨在按字母顺序"而不是严格按词法顺序对字符串进行排序,对于某些按字母顺序的定义.

I have a question related to string comparison vs. character comparison.

Characters > and 0 (zero) have following decimal values 62 and 48 accordingly.

When I compare two characters in the following code, I get value True (which is correct)

Console.WriteLine('>' > '0');

When I compare two one-character strings in the following code, I get value -1 which indicates that ">" is less than "0" (default culture is English)

Console.WriteLine(string.Compare(">", "0"));

Whereas comparison of "3" and "1" (51 and 49 code values) in the following code returns 1 (as expected)

Console.WriteLine(string.Compare("3", "1"));

Also, string.Compare(string str1, string str2) documentation says:

The comparison uses the current culture to obtain culture-specific information such as casing rules and the alphabetic order of individual characters

Would you be able to explain (or provide reference to some documentation) how string comparison is implemented e.g. how alphabetic order of individual characters is calculated etc?

解决方案

When you compare the characters '>' and '0', you are comparing their ordinal values.

To get the same behaviour from a string comparison, supply the ordinal string comparison type:

  Console.WriteLine(string.Compare(">", "0", StringComparison.Ordinal));
  Console.WriteLine(string.Compare(">", "0", StringComparison.InvariantCulture));
  Console.WriteLine(string.Compare(">", "0", StringComparison.CurrentCulture));

The current culture is used by default, which has a sorting order intended to sort strings 'alphabetically' rather in strictly lexical order, for some definition of alphabetically.

这篇关于字符串比较和单个字符的字母顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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