C# program to remove duplicate characters from String
Here's a C# program that removes duplicate characters from a given string:
using System;
using System.Text;
class Program
{
static void Main()
{
string inputString = "Hello, World!";
string resultString = RemoveDuplicates(inputString);
Console.WriteLine("String after removing duplicates: " + resultString);
}
static string RemoveDuplicates(string inputString)
{
StringBuilder stringBuilder = new StringBuilder();
foreach (char c in inputString)
{
if (stringBuilder.ToString().IndexOf(c) == -1)
{
stringBuilder.Append(c);
}
}
return stringBuilder.ToString();
}
}
In this program, we have the 'RemoveDuplicates' method that takes a string as input and returns a new string with duplicate characters removed.
We create a 'StringBuilder' object named 'stringBuilder' to efficiently build the resulting string without creating multiple intermediate strings.
We iterate through each character 'c' in the input string. Inside the loop, we check if the character 'c' is already present in the 'stringBuilder' by using the 'IndexOf' method to search for the character. If the character is not found (i.e., the index is -1), we append it to the 'stringBuilder'.
Finally, we return the resulting string by converting the 'stringBuilder' to a regular string using the 'ToString' method.
In the example above, the output would be:
String after removing duplicates: Helo, Wrd!
The duplicate characters 'l' and 'o' are removed from the input string "Hello, World!"