remove duplicate words from string in C#

前端 未结 4 552
猫巷女王i
猫巷女王i 2020-12-19 20:05

here is my code:

class Program
    {
        static void Main(string[] args)
        {
            string sentence = string.Empty;
            sentence = Con         


        
相关标签:
4条回答
  • 2020-12-19 20:23

    Use System.Linq Distinct:

    foreach (string s in x.Distinct())
    
    0 讨论(0)
  • 2020-12-19 20:32

    This should do everything you're asking:

    class Program
    {
        static void Main(string[] args)
        {
            string sentence = string.Empty;
            sentence = Console.ReadLine();
    
            var sent = sentence
                .Split(' ')
                .Distinct()
                .OrderBy(x => x);
    
            foreach (string s in sent)
            {
                Console.WriteLine(s.ToLower());
            }
    
            Console.ReadLine();
        }
    }
    

    Hope it helps!

    0 讨论(0)
  • 2020-12-19 20:35

    Use Distinct:

    foreach (string s in x.Distinct())
    {
            Console.WriteLine(s.ToLower());
    }
    
    0 讨论(0)
  • 2020-12-19 20:47

    You could use Linq's Distinct extension method:

    var sent = sentence.Split(' ').Distinct();
    

    You can also use this to ignore the case of strings when comparing them—e.g. "WORD" and "word" would be considered duplicates:

    var sent = sentence.Split(' ').Distinct(StringComparer.CurrentCultureIgnoreCase);
    
    0 讨论(0)
提交回复
热议问题