Count duplicate characters from String?



Count duplicate characters from String?

A string Can Contained two or more character in it, but we want to have only one
For Example
Required input and output
Input: Csharpstar
Output: Csharpt
Input: Ganga
Output: Gang
Input: Yahoo
Output: Yaho
Input: ganga
Output: gan
Solution:
You can achieve this by two ways 
1.     One by for loop
2.     Using index of method IndexOf(ch)





Step 1:
public string DuplicateChar(String Str)
        {
            int Count = 0;
            //Str = Str.ToUpper();
            for (int i = 0; i <= Str.Length - 1; i++)
            {
                for(int j=i+1;j<=Str.Length-1;j++)
                {
                    if (Str[i] == Str[j])
                    {
                        Count++;

                    }
                }
            }

            return Count.ToString();
        }
static void Main(string[] args)
        {

            String Name = "Ganga";
            Program obj = new Program();
            Console.WriteLine("Total Duplicate value"+ obj.DuplicateChar(Name));
            Console.ReadLine();
        }
Step 2:
public string DuplicateCharCount(String Str)
        {
            string repeat = "";
            int No = 0;
           // Str = Str.ToUpper();
            foreach (Char ch in Str)
            {
               
                if (repeat.IndexOf(ch) == -1)
                {
                    No++;
                }
                repeat += ch;
            }
            return(Str.Length- No).ToString();
        }



Share:

No comments:

Post a Comment

Popular

Tags

Mobile

Recent Posts