C#如何将用户输入的短语存储到字符串数组中?

时间:2013-11-28 03:19:26

标签: c# arrays string

我正在编写一个程序来扰乱用户输入的短语。我有大部分编码,但我想将用户输入的短语的字符串存储到数组中,短语的每个单词都存储为一个单独的元素。 这似乎是一件简单的事情,但我想不出办法来做到这一点。有人能帮助我吗?

到目前为止它是这样的:

    static void Main(string[] args)
    {
        bool success = false;
        string phrase = "";
        string [] phraseArray;

        Console.WriteLine("Welcome to the Word Scrambler!\n\n");
        do
        {
            Console.WriteLine("Enter a phrase between 10 and 60 character long:\n\t");
            phrase = Console.ReadLine();
            if (phrase.Length - 1 <= 10 || phrase.Length - 1 >= 60)
            {
                Console.WriteLine("You must enter a phrase with a length between 10 and 60!");
                success = false;
            }
            phraseArray = new string[phrase.Length - 1];

            // String (phrase) into string [] phraseArray ?

            Console.WriteLine("See below for your scrambled phrase:");
            for (int i = 0; i < phrase.Length - 1; i++)
            {
                Console.Write("{0} ", phraseArray[i]);
            }

            Console.WriteLine("Press any key to scramble another word or the 'Esc' key to exit...");
            if (Console.ReadKey(true).Key == ConsoleKey.Escape)
                success = false;
        } while (!success);`

3 个答案:

答案 0 :(得分:2)

考虑以下内容......

string[] words = sentence.Split(' ');

祝你好运!

答案 1 :(得分:1)

phraseArray  = phrase.Split();

或者如果您需要删除空字符串

phraseArray  = phrase.Split(new char[] {' '}, StringSplitOptions.RemoveEmptyEntries);

答案 2 :(得分:0)

每次要保存短语时,只需执行以下操作:

phrase+= inputString + ";";

之后你可以将短语分成字符串数组:

string[] yourStringArray = phrase.split(';');