0

I am trying to find the number of duplicate characters in an array and list them. For example, the user enters "this is my house", the output should look like this:

Number of duplicate characters is: 3 and the duplicates are: h i s

I have to use ToCharArray()

I've been trying but I can't get it to work properly, can you please help?

Thanks

Here is my code:


using System;
class Program
{
    static void Main()
    {
        Console.Write("type a sentence: ");
        String str = Console.ReadLine();
        char[] arr = str.ToCharArray();

        for (int j = 0; j < arr.Length; j++)
        {
            for (int k = j + 1; k < arr.Length; k++)
            {
                if (arr[j] == arr[k] && j != k)
                {
                    Console.WriteLine("number of duplicates: " + k + "\n" + "duplicates are: " + arr[j]);
                    Console.ReadLine();
                }
            }
        }
    }
}

1

5 Answers 5

5

You can try to use linq instead of for loop.

GroupBy make a group and use where get count greater than 1.

var r= str.Replace(" ", "").GroupBy(_ => _).Where(x => x.Count() > 1).Select(x => x.Key);

then use string.Join method and linq count instead of a loop to get your expect result.

Console.Write("type a sentence: ");
String str = Console.ReadLine();


var result = str.Replace(" ", "")
     .GroupBy(_ => _)
     .Where(x => x.Count() > 1)
     .Select(x => x.Key);


Console.WriteLine("number of duplicates: " + result.Count() + "\r" + "duplicates are: " + string.Join(" ",result));

c# online

Result

type a sentence: number of duplicates: 3  duplicates are: h i s
Sign up to request clarification or add additional context in comments.

2 Comments

thanks but I can't use Linq, this is an assignment and we are limited, I have to use a simple code like the above, my issue is that I can't get it to count or list properly.
@Nas Ok I edit my answer it can show like your expect result
0

Here is another solution without linq:

static void Main(string[] args)
{
    string longText = @"your sentence comes here";
    foreach (var character in CharacterCount.Count(longText))
    {
        if(character.Value>1)
           Console.WriteLine("{0} - {1}", character.Key, character.Value);
    }    
}

class CharacterCount
{
    public static SortedDictionary<char, ulong> Count(string stringToCount)
    {
        SortedDictionary<char, ulong> characterCount = new SortedDictionary<char, ulong>();

        foreach (var character in stringToCount)
        {
            if (!characterCount.ContainsKey(character))
                characterCount.Add(character, 1);
            else
                characterCount[character]++;
        }
        return characterCount;
    }   
}  

1 Comment

Consider using TryGetValue rather than ContainsKey.
0

This may help.

    Console.Write("type a sentence: ");
    String str = Console.ReadLine();
    char[] arr = str.ToCharArray();

    int[] count = new int[10000];

    for (int j = 0; j < arr.Length; j++)
    {
        if( arr[j] >= 'a' && arr[j] <= 'z' || arr[j] >= 'A'&& arr[j] <= 'Z' )
        {
            count[arr[j]]++;
        }
    }

    int ans=0;
    for (int j = 0; j < count.Length; j++)
    {
        if(count[j]>1)
        {
            ans++;              
        }
    }

    Console.Write("Number of duplicates: " + ans +" duplicates are: ");

    for (int j = 0; j < count.Length; j++)
    {
        if(count[j]>1)
        {
            Console.Write((char)j +" " );
        }
    }
    Console.WriteLine();
}

1 Comment

Thanks Chameera, it works, just couple of notes, it is taking the Space as a character (for example "this is my house" is showing as 4 duplicates instead of 3), how can we avoid that. and also is it possible to list the duplicates on the same line instead of each on a separate line?
0
This Find to find Duplicates characters And Its Occurrence and I am using Key value pair in C# 
    /// <summary>
    /// Find The Duplicates And Its Occurrence
    /// </summary>
    /// <param name="inputString"> input String for example 
    /// "Aassekoopannessyttoodde","Mississippi","raccoonnookkeeper"</param>
    private static void FindTheDuplicatesAndItsOccurrence(string inputString)
    {
        // we used Dictionary to make this collection generic  
        Dictionary<Char, int> CharCount = new Dictionary<char, int>();

        foreach (Char eachLetter in inputString)
        {
            if (eachLetter != ' ')
            {
                if (!CharCount.ContainsKey(eachLetter))
                {
                    CharCount.Add(eachLetter, 1);
                }
                else
                {
                    CharCount[eachLetter]++;
                }
            }
        }
        
        foreach (var item in CharCount)
        {
            if (item.Value > 1)
            {
                Console.WriteLine(item.Key + "," + item.Value);
            }
            
        }
    }

Comments

0

Finding duplicate characters and there count using linq

using System;
using System.Linq;
using System.Collections.Generic;
                    
public class Program
{
    public static void Main()
    {
        string myName = "Hussamuddin";
        List<char> elementCount =  new List<char>(myName.ToCharArray());
        var mycount = elementCount.Where(x => myName.Contains(x)).GroupBy(x=>x).Where(x => x.Count()>1).Select(x => x.Key + ":" + x.Count().ToString()).ToList();
        mycount.ForEach(x => Console.WriteLine(x));
    }
}

Output:

u:2
s:2
d:2

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.