按第一个字母对字符串排序 [C]

发布于 2024-08-27 14:45:56 字数 174 浏览 4 评论 0原文

我有一个程序,它根据结构存储在其中的“名称”将结构放置在链接列表中。

为了找到它们在列表中的位置,我需要弄清楚我插入的名称在字母表中是否比其旁边的结构中的名称早或晚。

这些名称位于我可以访问的结构内部。 如果这需要更多工作,我不需要完整的比较,即使只是第一个字母也可以。

感谢您的帮助!

I have a program which places structures in a linked list based on the 'name' they have stored in them.

To find their place in the list, i need to figure out if the name im inserting is earlier or later in the alphabet then those in the structures beside it.

The names are inside the structures, which i have access to.
I don't need a full comaparison if that is more work, even just the first letter is fine.

Thanks for the help!

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

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

发布评论

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

评论(4

烂柯人 2024-09-03 14:45:56

我不清楚你的问题是什么,但这样的事情会起作用:

if (node1->name[0] <= node2->name[0]) {
  ...
} else {
  ...
}

这将比较每个节点中名称的第一个字母。

It's not clear to me what your question is, but something like this would work:

if (node1->name[0] <= node2->name[0]) {
  ...
} else {
  ...
}

This will compare the first letter of the name in each of the nodes.

贱贱哒 2024-09-03 14:45:56

如果您有两个 C 字符串,ab,您可以简单地比较它们的第一个元素:

*a == *b

其中 == 可以是六个关系中的任何一个运营商。

请记住,对于 C 字符串,char* 指向字符串中的第一个字符。

If you have two C strings, a and b, you can simply compare their first elements:

*a == *b

Where == can be any of the six relational operators.

Remember that with C strings, the char* points to the first character in the string.

很糊涂小朋友 2024-09-03 14:45:56

strcmp() 比较两个 C 字符串,并告诉您它们的顺序,或者它们是否相同。如果您不关心大小写,可以使用strcasecmp()。这些函数不会比较任何超出确定返回顺序所需的字符串。

strcmp() compares two C strings and will tell you what order they're in, or if they're the same. If you don't care about case, you can use strcasecmp(). These functions won't compare any more of the strings than necessary to determine what order to return.

浅黛梨妆こ 2024-09-03 14:45:56

您可以简单地迭代列表,并根据传递每个元素时进行的比较将新元素插入到正确的位置。最简单的区分大小写的版本只需比较字母的数值即可完成(例如 a[0] < b[0]),或者如果需要,您可以将两者转换为常见的大小写不区分大小写(参见ctype.h)。或者您可以使用 strcmp 比较整个单词。

You can simply iterate through the list and insert the new element in the correct place based on comparisons you do while passing each element. The simplest case sensitive version can be done just by comparing the numeric values of the letters (e.g. a[0] < b[0]), or you can convert both to a common case if you want to be case-insensitive (see ctype.h). Or you can compare the whole words with strcmp.

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