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:
- The first step is to check whether the current character is a whitespace. If it is, we use the
continuekeyword to skip the rest of the loop iteration and move on to the next character. - If the character is not a space, we check whether the
charCountdictionary 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;.
- If it does, we increment its count using
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.