I have the below code which is supposed to ask for a user input values to be entered of various integers separated by "#" like 1#2#3##2 and so on. It is then eventually supposed to find the values in the sequence entered that have repeats and display it like "the sequence contains 2 repeated value."
However I am not sure if the code I have used to separate the user entered value is correct as it displays an error:
public class Program
{
public static void Main(string[] args)
{
// Keep the following line intact
Console.WriteLine("===========================");
// Insert your solution here.
// user input gets the input from the user
// regarding a line where integers are separated by #
String userInput;
Console.WriteLine("Please enter single line containing a list of integers, separated by '#':");
userInput = Console.ReadLine();
// splitting the userInput into Array of Strings
if (userInput != null)
{
// splitting the userInput by #
String[] numberStrings = userInput.Split("#");
// numbers list contain the list of unique numbers
List<int> numbers = new List<int>();
// takes count of duplicate numbers
int totalDuplicateNumbers = 0;
// adding the number string to the list after converting to int
for (int i = 0; i < numberStrings.Length; i++)
{
numbers.Add(Int32.Parse(numberStrings[i]));
}
// now sorting the number list
numbers.Sort();
bool duplicatePresent = false;
for (int i = 0; i < numbers.Count - 1; i++)
{
if (numbers[i] == numbers[i + 1])
{
if (!duplicatePresent)
{
duplicatePresent = true;
totalDuplicateNumbers += 1;
}
}
else
{
duplicatePresent = false;
}
}
// display result
Console.WriteLine($"The sequence contains {totalDuplicateNumbers} repeated values.");
}
else
{
Console.WriteLine("Wrong input");
}
// Keep the following lines intact
Console.WriteLine("===========================");
}
}
>Solution :
Your code is not correct. Split
expects one or more characters to split by. You passed a string. Pass a character, like this:
String[] numberStrings = userInput.Split('#');
Please note that this solution will fail on your test input of
1#2#3##2
Because that means that there are the strings "1", "2", "3", "", "2"
and ""
will fail in your subsequent parsing attempt.
You may want to try
String[] numberStrings = userInput.Split('#', StringSplitOptions.RemoveEmptyEntries);
This removes the empty, non-number entries. Whether that is what your exercise wants you to do, or if you should do something else with the empty input, is something only you can answer.