Tuesday, August 8, 2023

C# Program to Remove All Duplicate Characters in a String

 

C# Program to Remove All Duplicate Characters in a String



// C# program to remove duplicate character
// from character array and print in sorted
// order
using System;
using System.Collections.Generic;
class GFG 
{
static String removeDuplicate(char []str, int n)
{
    // Used as index in the modified string
    int index = 0;
  
    // Traverse through all characters
    for (int i = 0; i < n; i++)
    {
  
        // Check if str[i] is present before it 
        int j;
        for (j = 0; j < i; j++) 
        {
            if (str[i] == str[j])
            {
                break;
            }
        }
  
        // If not present, then add it to
        // result.
        if (j == i) 
        {
            str[index++] = str[i];
        }
    }
    char [] ans = new char[index];
    Array.Copy(str, ans, index);
    return String.Join("", ans);
}
  
// Driver code
public static void Main(String[] args)
{
    char []str = "geeksforgeeks".ToCharArray();
    int n = str.Length;
    Console.WriteLine(removeDuplicate(str, n));
}
}
// C# program to remove duplicate character
// from character array and print in sorted
// order
using System;
using System.Collections.Generic;
  
  
public class GFG{
  
static char []removeDuplicate(char []str, int n)
{
      
    // Create a set using String characters
    // excluding '�'
    HashSet<char>s = new HashSet<char>(n - 1);
    foreach(char x in str)
        s.Add(x);
          
    char[] st = new char[s.Count];
      
    // Print content of the set
    int i = 0;
    foreach(char x in s)
       st[i++] = x;
    
    return st;
}
  
// Driver code
public static void Main(String[] args)
{
   char []str= "geeksforgeeks".ToCharArray();
   int n = str.Length;
     
   Console.Write(removeDuplicate(str, n));
}
  
// This code contrib
uted by



No comments:

Post a Comment

NET Core Code Security, Authorization/Authentication, and code architecture

Complex NET Core interview questions (Code Security, Authorization/Authentication, and code architecture)  _________________________________...