字符串数组以abc顺序排序

时间:2015-02-07 22:40:56

标签: c# arrays loops if-statement alphabetical

这是我的代码和评论。所以即时退出循环有困难。我知道如果(contd = true)或其他东西它应该退出,但如果他们进入Y继续,我怎么回到循环? 另一件事是如何按abc顺序对此进行排序。然后我如何从Z-A做反向。谢谢你的帮助,在这里毫无头绪的初学者。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
class Program
{
    static void Main(string[] args)
    {
        string lastName;
        string [] lastName = new string[];    //array list of last names
        int index;
        string contd;


        for (index=0;index++)
        {
            Console.Write("Enter a last name: ");
            lastName[index] = Convert.ToString(Console.ReadLine());
            Console.Write("Keep going? (Y/N): ");   
//prompts user to keep inputting or exit out
                contd = Convert.ToString(Console.ReadLine());
                if (contd = "n"(Console.ReadLine());
            {
                //exit out of last name input
            }
            else contd = "y"(Console.ReadLine());
            {
                //go back into last name input
            }
        }

        Console.WriteLine((index+1) + " last names entered");       
//shows how many last names were entered

        Console.WriteLine();                    //spacing

        //display last names
        Console.WriteLine("Names in Acsending Order"); Console.WriteLine(); 

        for(index=0; index++)                   
//shows the last names in order from A-Z (acsending)
        {
            Console.WriteLine(lastName[index]);
        }

        Console.WriteLine();

        Console.WriteLine("Names in Descending Order"); Console.WriteLine();

        for(index=0; index--)               
//shows back last names in reverse order Z-A (descending)
        {
            Console.WriteLine(lastName[index]); Console.WriteLine();

        }
        Console.ReadLine();







    }
}
}

2 个答案:

答案 0 :(得分:1)

您可以使用do while循环:

string d = string.Empty;

do
{
    Console.WriteLine("What's your answer?");
    d = Console.ReadLine();
}
while (d != "Y");

对于排序,您可以使用Array.Sort

Array.Sort(array);

答案 1 :(得分:0)

您正在进行分配而不是比较,并且还使用分号结束了if语句行。赋值只是将contd设置为n,而不是检查它是否是它的当前值,并且末尾的分号将完全忽略以下括号..

if(contd == "n")
    ;

哪个是有效的代码(不知道你为什么要这样做)。以下是您正在寻找的内容,但我仍然认为您的for循环有点奇怪

contd = Console.ReadLine(); // Already a string..
if (contd == "n")
{
    //exit out of last name input
    break;
}
else
{
    //go back into last name input
}

要按字母顺序对这些名称进行排序,最好查看排序算法,例如冒泡排序。你总是可以使用linq,但我想这不在你的类范围

lastName = lastName.OrderBy(x => x).ToArray();
lastName = lastName.OrderByDescending(x => x).ToArray();