Selenium C sharp Question 2 – Find duplicates from String and return

Here is selenium c# script below to find duplicates in string and return the duplicates:

using System;
using System.Collections.Generic;
 
class Program
{
    static void Main()
    {
        string str = "Testing automation";
        Dictionary<char, int> charCount = new Dictionary<char, int>();
 
        foreach (char c in str.ToLower()) // optional: make it case-insensitive
        {
            if (char.IsWhiteSpace(c)) continue; // skip spaces
 
            if (charCount.ContainsKey(c))
                charCount[c]++;
            else
                charCount[c] = 1;
        }
 
        Console.WriteLine("Duplicate characters:");
        foreach (var pair in charCount)
        {
            if (pair.Value > 1)
                Console.WriteLine($"{pair.Key} : {pair.Value}");
        }
    }
}

Explanation:

In the Main block of the class, we start by initializing a string variable str with the value "Test Automation". We also declare a dictionary named charCount, where each key is a character (char) and the corresponding value is an integer (int) representing the count of that character.

Next, we use a foreach loop to iterate through each character in the string. Inside the loop:

  1. The first step is to check whether the current character is a whitespace. If it is, we use the continue keyword to skip the rest of the loop iteration and move on to the next character.
  2. If the character is not a space, we check whether the charCount dictionary already contains this character as a key.
    • If it does, we increment its count using charCount[c]++;.
    • If it doesn’t, we add the character to the dictionary with an initial count of 1 using charCount[c] = 1;.

After the loop completes, the charCount dictionary will contain the frequency of each non-whitespace character in the string.

In the next step, we iterate through the charCount dictionary. For each key-value pair, we check if the count (value) is greater than 1. If so, we print the character and its count using:

csharpCopyEditif (pair.Value > 1)
    Console.WriteLine($"{pair.Key} : {pair.Value}");

This final step outputs only the characters that appear more than once in the string, along with the number of times they occur.


0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Testingtalkslatest.com - A project by CreativeHub IT Solutions.
Contact Us At: support@testingtalkslatest.com
Our Partner websites - Classified Hub , CodesToolbox , Smart Fitness Guide , CodesToolbox , Testing Forum
Scroll to Top
0
Would love your thoughts, please comment.x
()
x