[英]Do < and > on C++ strings reflect alphabetical ordering?
I have a question about alphabetical order of strings in C++. 我有一个关于C ++中字符串的字母顺序的问题。 Let us say i have two strings:
我们说我有两个字符串:
string x="asd123";
string y="asd136";
Can we compare these strings with < or > operators? 我们可以用<或>运算符比较这些字符串吗? For example: can we say
例如:我们可以说
if(x>y)
cout<<".....";
Does that always work?
The strings are compared lexicographically (dictionary style), with a string that's a shorter subset of another string coming before the longer one. 字符串按字典顺序(字典样式)进行比较,字符串是较长字符串之前的另一个字符串的较短子集。 But it's not necessarily alphabetical ;
但它不一定按字母顺序排列 ; it's according to the underlying character encoding.
它是根据底层字符编码。 Most systems these days use ASCII, so lowercase letters come out in order, and uppercase characters come out in order, and uppercase characters come before lowercase characters.
现在大多数系统都使用ASCII,因此小写字母按顺序排列,大写字符按顺序排出,大写字符排在小写字符之前。
Yes, comparing std::string
s with std::string::operator>
always works. 是的,将
std::string
s与std::string::operator>
始终有效。 The strings are compared lexicographically . 字符串按字典顺序进行比较。 This means that each corresponding element of the two strings is compared in turn until two are found that are not equal, and that ordering determines the order of the strings.
这意味着依次比较两个字符串中的每个对应元素,直到找到两个不相等的元素,并且该排序确定字符串的顺序。
The lexicographic ordering performs <
on each element of the std::basic_string
. 词典排序对
std::basic_string
每个元素执行<
。 That is, for a std::string
, each char
will be compared using <
. 也就是说,对于
std::string
,将使用<
来比较每个char
。 It will simply compare the values of those char
s. 它将简单地比较这些
char
的值。 As far as C++ is concerned, a char
is just a numeric value. 就C ++而言,
char
只是一个数值。 These values are mapped to the characters in a string literal by the execution character set (which, for a modern C++ compiler, is almost always at least ASCII compatible). 这些值通过执行字符集映射到字符串文字中的字符 (对于现代C ++编译器,它几乎总是至少与ASCII兼容)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.