0

I was trying to create a list from a user input with something like this:

Create newlist: word1, word2, word3, etc...,

but how do I get those words one by one only by using commas as references going through them (in order) and placing them into an Array etc? Example:

        string Input = Console.ReadLine();

        if (Input.Contains("Create new list:"))
        {
            foreach (char character in Input)
            {
                if (character == ',')//when it reach a comma
                {
                    //code goes here, where I got stuck...
                }
            }
        }

Edit: I didn`t know the existence of "Split" my mistake... but at least it would great if you could explain me to to use it for the problem above?

zeta12900
  • 31
  • 3

2 Answers2

7

You can use this:

String words = "word1, word2, word3";

List:

List<string> wordsList= words.Split(',').ToList<string>();

Array:

string[] namesArray = words.Split(',');
Catarina Ferreira
  • 1,824
  • 5
  • 17
  • 26
0

@patrick Artner beat me to it, but you can just split the input with the comma as the argument, or whatever you want the argument to be.

This is the example, and you will learn from the documentation.

    using System;

    public class Example {

    public static void Main()    {
          String value = "This is a short string.";
          Char delimiter = 's';
          String[] substrings = value.Split(delimiter);
          foreach (var substring in substrings)
             Console.WriteLine(substring);
    } 
} 

The example displays the following output:

Thi 
i 
a 
hort 
tring.
Stephen Kennedy
  • 20,585
  • 22
  • 95
  • 108
Chris
  • 153
  • 2
  • 15