Hippimaster Hippimaster - 14 days ago 7
C# Question

How to register a user input to a list C#

Hi im trying to get a user to make a list of words. Next step is for the user to type one of the words again and then the program will check for anagrams in the list. I have found a way to solve it but ONLY when checking my own list.
I would like to know how to do what I need. no need for exact code answear just some help on the way. Still New at C# and coding. Dont mind the swedish comments.

static void Main(string[] args)
{
Console.WriteLine("Skriv lite olika ord:");
string[] words = Console.ReadLine().Split(null);
Console.WriteLine("Tackar! Välj ett av orden för att kolla ifall det finns Anagram ordet:");
string[] word = Console.ReadLine().Split(null);

List<string> result = new List<string>();
bool match = false;


for (int i = 0; i < words.Length; i++)
words[i] = words[i].Trim();

//Loopar igenom alla ord i arrayen, börjar med första ordet.
for (int i = 0; i < words.Length - 1; i++)
{
result.Add(words[i]);
//Loopar igenom arrays med nästkommande ord.
for (int c = 2; c < words.Length; c++)
{
//Gämför bara ifall orden har lika många bokstäver och struntar i "tomma" ord
if(words[i].Length == words[c].Length && words[i] !="")
{
//Konverterar orden till CharArray
char[] a = words[i].ToUpper().ToCharArray();
char[] b = words[c].ToUpper().ToCharArray();
//Soreterar orden i bokstavsordning
Array.Sort(a);
Array.Sort(b);

match = false;
//sätter en counter för att kunna räkna
int counter = 0;
//Loppar igen alla bokstäver i orden man jämför
// Om den hittar någon bokstav som inte stämmer överens så returners False.
// Om alla bokstäver mathar så return true.
foreach(char x in a)
{
if (x == b[counter])
match = true;
else
{
match = false;
break;
}
counter++;
}
// om alla bokstäver "matchar" så läggs de till i listan
// har words[c] = ""; ifall den hittar tomma strings
if(match)
{
result.Add(words[c]);
words[c] = "";
}
}
}
// om listan bara blir 1 ord så hittas ingen match
if (result.Count() > 1 && result[0] != "")
{
Console.Write("Anagrams: ");
foreach (string s in result)
Console.Write(s + " ");
Console.WriteLine();
}
//återställer listan
result.Clear();
}
Console.ReadKey();

Answer

The solution is actually quite simple.
You just have to check every word which fits the amount of letters, if they share the same letters.

E.g. word has 4 letters. If a user types in what which has 5 letters they can't possible match. But if he types in darn which is also 4 u just have to check if all letters match.

One should keep an eye on Case-Sensitivity, which I left out to make the answer more simple.
As well there are numerous ways to improve this code which i left out. All in the name of simplicity :)

    static void Main(string[] param)
    {
        //The list of Words which are anagrams
        List<string> solutions = new List<string>();

        //get the user input
        string userInput = "User writes arm ram kola like hi"; //Replace with Console.ReadLine().ToLower(); and don't forget to prompt the userwith input

        //split it into the diffrent words
        string[] words = userInput.Split(' ');

        //get the users "match want"
        string userMatchWant = "mar"; //Replace with Console.ReadLine().ToLower(); and don't forget to prompt the userwith input

        //Find words wich are as long as mar
        foreach (string word in words)
        {
            //if they arn't the same length it can't be an anagramm
            if (word.Length != userMatchWant.Length)
                continue;

            //To Determin if all characters of the words are the same
            bool hasOnlyTheSameLetters = false;

            //now check if all characters contains
            foreach (char c in word)
            {
                //If The lette is in the word assume it contains only of the letters that we are looking for, because
                if (userMatchWant.Contains(c.ToString()))
                    hasOnlyTheSameLetters = true;
                //else we know it has a different word so we can breack and check the other input words.
                else
                {
                    hasOnlyTheSameLetters = false;
                    break;
                }                        
            }

            //if there is a diffrence in letters contine
            if (hasOnlyTheSameLetters == false)
                continue;
            //else add the word to the solution
            else
                solutions.Add(word);
        }

        //Print the solutions
        if(solutions.Count > 0)
        {
            Console.Write("Anagrams: ");
            foreach (string s in solutions)
                Console.Write( s  + " ");
            Console.WriteLine();
        }

        Console.ReadKey();
    }

For all you LINQ fanatics out there, this is the shortest way I could come up with, to replace the foreach(string word in words) - Loop:
var totalMatches = words.Where(p => p.Length == userMatchWant.Length).Where(p => p.All(c => userMatchWant.Contains(c.ToString())));