在 C 中对包含大写和小写字母的字符串数组进行排序

发布于 2024-09-19 23:33:36 字数 255 浏览 2 评论 0原文

有没有一种方法可以按字母顺序对字符串数组进行排序,其中字符串同时包含大写和小写字母?

因为大写字母的 ASCII 值较低,所以像 strcmp 这样的函数总是会显示它位于小写字母之前。例如,假设我们想要对“ABCD”、“ZZZZ”、“海龟”、“JAVA”、“水”进行排序。

当使用strcmp这样的函数对这些字符串进行排序时,就变成:

ABCD 爪哇 ZZZZ 龟 水

应该是:

ABCD 爪哇 龟 水 ZZZZ

Is there a way to sort an array of strings in alphabetical order where the strings contain both capital and lowercase letters?

Because capital letters have a lower ASCII value so functions like strcmp would always show that it is before a lower case letter. For example, lets say we wanted to sort "ABCD", "ZZZZ", "turtle", "JAVA", "water".

When using functions like strcmp to sort these strings, it becomes:

ABCD
JAVA
ZZZZ
turtle
water

when it should be:

ABCD
JAVA
turtle
water
ZZZZ

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

一个人练习一个人 2024-09-26 23:33:37

严格使用 C89 的简单自己的解决方案应该有所帮助:

#include <ctype.h>
#include <string.h>

int strcmpIgnoreCase(const char *a,const char *b)
{
  while( *a && *b )
  {
    register r=tolower(*a)-tolower(*b);
    if( r )
      return r;
    ++a;
    ++b;
  }
  return tolower(*a)-tolower(*b);
}

a simple own solution in strictly C89 should help:

#include <ctype.h>
#include <string.h>

int strcmpIgnoreCase(const char *a,const char *b)
{
  while( *a && *b )
  {
    register r=tolower(*a)-tolower(*b);
    if( r )
      return r;
    ++a;
    ++b;
  }
  return tolower(*a)-tolower(*b);
}
別甾虛僞 2024-09-26 23:33:36

使用 qsort 和 strcasecmp 或 strcoll 作为比较函数。

strcasecmp 可能更快,但 strcoll 更灵活,并且使用程序区域设置,以便非 ASCII 字符串可以工作。

Use qsort with either strcasecmp or strcoll as the compare function.

strcasecmp is likely to be faster, but strcoll is more flexible and uses the programs locale so that non-ASCII strings work.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文