User input then split string

拟墨画扇 提交于 2021-02-05 09:39:38

问题


I have looked online for many solutions to my problem. I want to ask the user to input a sentence and write the sentence out one word per line using the split method. I have asked the user to enter a sentence and ran the console but the the sentence keeps appearing on the second line.

namespace Seperation
{
    class Program
    {
        static void Main()
        {

            string temp;
            string sentenceTwo = (" ");

            Console.WriteLine("please enter a sentence");
            temp = Console.ReadLine();
            sentenceTwo = temp;

            string[] split = sentenceTwo.Split(',');
            foreach (string item in split)
            {
                Console.WriteLine(item);
            }
            Console.ReadLine();        
        }
    }
}

回答1:


You should split the string on space instead of on comma:

namespace Seperation
{
    class Program
    {
        static void Main()
        {
            string temp;
            string sentenceTwo = (" ");

            Console.WriteLine("please enter a sentence");
            temp = Console.ReadLine();
            sentenceTwo = temp;

            string[] split = sentenceTwo.Split(' ');
            foreach (string item in split)
            {
                Console.WriteLine(item);
            }
            Console.ReadLine();        
        }
    }
}



回答2:


You are currently splitting by a comma , only when you need to split by punctuations that may exist in a sentence like space " " comma "," and peroid "."

//..other code
string[] split = sentenceTwo.Split(new char[]{' ', '.', ','}, System.StringSplitOptions.RemoveEmptyEntries);
foreach (string item in split)
{
    Console.WriteLine(item);
}
//..other code


来源:https://stackoverflow.com/questions/36394475/user-input-then-split-string

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!