C 字符串的比较运算符
我在查找比较 C 字符串的信息时遇到一些困难。我知道与 C++ 不同,C 不支持运算符重载,所以我想知道是否有任何方法可以检查一个字符串是否大于/小于另一个字符串(例如 str1 > str2)?
提前感谢您的回复。老实说,这是我第一次真正不得不问问题,因为我找不到相关的帖子。
I am having some difficulty locating information of comparing C strings. I understand that unlike C++, C does not support operator overloading, so I'm wondering if there is any way to check if one string is greater/less than another (e.g. str1 > str2)?
Thanks ahead of time for your responses. This is honestly one of the first times I have actually had to ask a question because I could not find a related post.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
有几种,每种都有不同的用途(现在省略宽字符变体)。
strcmp
– 逐个字符地比较两个字符串(使用 C 语言中的字符串相等概念或不 - 这不需要与人类的思维方式一致 - 请参阅strcoll
)。有一个变体用于仅比较最多前 n 个字符,strncmp
。strcasecmp
– 比较两个字符串,忽略大小写。有一个变体用于仅比较最多前 n 个字符,strncasecmp
。strcoll
– 比较两个字符串,观察当前设置的区域设置(这就是为什么它被称为排序规则,在这种情况下不进行比较)。如果您希望ss
和ß
对于德国受众来说是相等的,那么您应该使用这个。在您可能
用语言编写的地方,您必须
用 C 编写。本质上,您将两个操作数移至函数调用中,保留比较运算符并与
0
进行比较。There are several, each serving different purposes (omitting wide character variants for now).
strcmp
– compares two strings, character by character (with the C notion of what strings are equal or not – that doesn't need to coincide with how humans think – seestrcoll
). There's a variant for comparing only the first at most n characters,strncmp
.strcasecmp
– compares two strings, ignoring case. There's a variant for comparing only the first at most n characters,strncasecmp
.strcoll
– compares two strings, observing the currently set locale (which is why it's called collation, not comparing in this case). If you wantss
andß
to compare equal for a German audience, then this is what you should use.Where you might write
in a language, you have to write
in C. Essentially you move both operands into the function call, retain the comparison operator and compare with
0
instead.在 C 中使用 strcmp()。
例如,如果要比较两个字符串 s1 和 s2,则
strcmp(s1,s2) 如果相等则返回 0,如果 s1 大于 s2,则返回正整数,如果 s1 小于 s2,则返回负整数比 s2.
Use strcmp() in C.
for example if you want to compare two strings s1 and s2 then,
strcmp(s1,s2) will return 0 if they are equal, positive integer if s1 is greater than s2 and negative integer if s1 is lesser than s2.