首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >我试着从数组中对单词进行排序,但不起作用

我试着从数组中对单词进行排序,但不起作用
EN

Stack Overflow用户
提问于 2017-08-29 04:06:08
回答 1查看 97关注 0票数 1

问题是它给出的单词是这样的:

代码语言:javascript
复制
zahlen zahlen z y wörter w sondern sind standard s r keine k junge j i hello hilla h g f e die diese bbbb bbba bbba a

例如,"hello“和"hilla”这两个词的位置应该改变,我不知道为什么它们是这样的。

我知道有一个用于字符的compareTo函数。我想知道为什么这会导致数组中的单词排序错误。

代码语言:javascript
复制
using System;
using System.Collections;

namespace WortArraySortieren
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("hello junge die standard zahlen sind keine zahlen sondern diese wörter hier ");

            string[] wordlist = new string[] {"hello","junge","die","standard","zahlen","sind","keine","zahlen","sondern","diese","wörter","hilla","a", "bbba", "bbbb", "bbba", "e", "f", "g", "h", "i", "j", "s", "w", "k", "z", "r", "y" };
            int length = wordlist.Length;

            for (int m = 0; m < wordlist.Length; m++)
            {
                for (int i = 0; i < wordlist.Length - 1; i++)
                {
                    string a = wordlist[i];
                    string b = wordlist[i + 1];

                    for (int e = 0; e < a.Length && e < b.Length;e++ )
                    {
                        char letter0 = a[e];
                        char letter1 = b[e];

                        if (letter0 < letter1)
                        {
                            string temp = wordlist[i + 1];
                            wordlist[i + 1] = wordlist[i];
                            wordlist[i] = temp;
                            break;
                        }
                    }
                }
            }

            for (int u = 0; u < wordlist.Length; u++)
            {
                Console.Write(wordlist[u] + " ");
            }

            Console.ReadLine();
        }
    }
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-08-29 04:13:43

尝试:

代码语言:javascript
复制
string[] wordlist = new string[] {"hello","junge","die","standard","zahlen","sind","keine","zahlen","sondern","diese","wörter","hilla","a", "bbba", "bbbb", "bbba", "e", "f", "g", "h", "i", "j", "s", "w", "k", "z", "r", "y" };

Array.Sort(wordlist, StringComparer.InvariantCulture);

for (int u = 0; u < wordlist.Length; u++)
{
  Console.Write(wordlist[u] + " ");
}

有关详细信息,请参阅https://msdn.microsoft.com/en-us/library/system.array.sort(v=vs.110).aspx

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/45926594

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档