1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94
|
using System;
using System.Collections.Generic;
using System.Linq;
namespace TestUnique
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Veuillez entrer une liste de mots séparés par des espaces :");
string phrase = Console.ReadLine();
string[] mots = phrase.Split(' ');
Console.WriteLine("Liste des mots (avec doublons) :");
foreach (string mot in mots)
{
Console.WriteLine("- {0}", mot);
}
Console.WriteLine("Liste des mots uniques (méthode du tri) :");
string[] copie = (string[])mots.Clone();
Array.Sort(copie);
string precedent = string.Empty;
foreach (string mot in copie)
{
if (mot != precedent)
{
precedent = mot;
Console.WriteLine("- {0}", mot);
}
}
Console.WriteLine("Liste des mots uniques (méthode \"naturelle\") :");
for (int i = 0; i < mots.Length; ++i)
{
bool doublon = false;
for (int j = 0; j < i; ++j)
{
if (mots[j] == mots[i])
{
doublon = true;
}
}
if (!doublon)
{
Console.WriteLine("- {0}", mots[i]);
}
}
Console.WriteLine("Liste des mots uniques en passant par un dictionnaire :");
Dictionary<string, string> dico = new Dictionary<string, string>();
foreach (string mot in mots)
{
try
{
dico.Add(mot, mot);
}
catch {}
}
foreach (KeyValuePair<string, string> mot in dico)
{
Console.WriteLine("- {0}", mot.Key);
}
Console.WriteLine("Liste des mots uniques par recopie :");
List<string> copie2 = new List<string>();
foreach (string mot in mots)
{
if (!copie2.Contains(mot))
{
copie2.Add(mot);
}
}
foreach (string mot in copie2)
{
Console.WriteLine("- {0}", mot);
}
Console.WriteLine("Liste des mots uniques en utilisant Linq :");
copie = mots.Distinct().ToArray();
foreach (string mot in copie)
{
Console.WriteLine("- {0}", mot);
}
Console.WriteLine("Il y a plein d'autres solutions possibles");
Console.ReadKey(true);
}
}
} |
Partager