You are getting the index of first occurrence of comma, then displaying it in the console.
You need String.Substring
method to get a substring from the user input.Substring
method takes index as parameter and then returns the substring starting from that index until the end of your string unless you provide a count parameter.
For example, this code will display , John
in the console:
string input = "Hello, John";
int index = input.IndexOf(',');
Console.WriteLine(input.Substring(index));
As you can see it also includes the character at the starting index (comma in this case, in order to avoid this you can just use input.Substring(index + 1)
instead of input.Substring(index)
Now, if we return your question, you can use a while
loop, and then get the substring starting the first comma,display it and update the value of userInput
on each iteration.And also use a variable to hold index
of the first comma in your string, so when it becomes -1
, you will know that there is no comma exists in your string, then you break the loop and display the last part:
string userInput = Console.ReadLine();
int index = userInput.IndexOf(','); // get the index of first comma
while (index != -1) // keep going until there is no comma
{
// display the current value of userInput
Console.WriteLine(userInput);
// update the value of userInput
userInput = userInput.Substring(index + 1).Trim();
// update the value of index
index = userInput.IndexOf(',');
}
Console.WriteLine(userInput); // display the last part
Note: I have also used String.Trim
method to remove trailing spaces from the userInput
.