C# Program to Remove All Duplicate Characters in a String
using System;
using System.Collections.Generic;
class GFG
{
static String removeDuplicate(char []str, int n)
{
int index = 0;
for (int i = 0; i < n; i++)
{
int j;
for (j = 0; j < i; j++)
{
if (str[i] == str[j])
{
break;
}
}
if (j == i)
{
str[index++] = str[i];
}
}
char [] ans = new char[index];
Array.Copy(str, ans, index);
return String.Join("", ans);
}
public static void Main(String[] args)
{
char []str = "geeksforgeeks".ToCharArray();
int n = str.Length;
Console.WriteLine(removeDuplicate(str, n));
}
}
|
using System;
using System.Collections.Generic;
public class GFG{
static char []removeDuplicate(char []str, int n)
{
HashSet<char>s = new HashSet<char>(n - 1);
foreach(char x in str)
s.Add(x);
char[] st = new char[s.Count];
int i = 0;
foreach(char x in s)
st[i++] = x;
return st;
}
public static void Main(String[] args)
{
char []str= "geeksforgeeks".ToCharArray();
int n = str.Length;
Console.Write(removeDuplicate(str, n));
}
}
No comments:
Post a Comment