I need to write a program that reads from a text file the first and last name. Then, I need to take up to 4 charaters of the first name and 4 charaters of the last name and combine them into a third string. The issue is that the new string must be unique.
eg.
First name = James
Last name = Jackson
new string would be JAMEJACK
First name = James
Last name = Jack
new string = JAMEJACK1
or new string = JAMSJACK
It doesn't matter how it is done, as long as all of the strings are unique.
LastName = input.Substring(12, 10);
FirstName = input.Substring(21, 21);
new string = LastName.Substring(0, 4) + FirstName.Substring(0, 4);
Sam Marion really gets the credit here for being the first to suggest it, but it was also the same line of thinking I had.
Why not use a Dictionary<string, int>
to store all the combined names, and the count of how many there are. Then once you build the Dictionary, you can just increment the number by how many duplicates you have. Something like this:
Dictionary<string, int> usernameCollection = new Dictionary<string, int>();
foreach(string name in namesTextFile)
{
string username = string.Concat(name.Split().Select(x => x.Length >= 4 ? x.Substring(0, 4) : x));
if(usernameCollection.ContainsKey(username))
{
usernameCollection[username] = usernameCollection[username] + 1;
}
else
{
usernameCollection.Add(username, 1);
}
}
I made a fiddle here to demonstrate.