How to remove characters present in first string from the second string in C#

3 Answers

0 votes
using System;

class Program
{
    static String removeChars(String s, String chars) { 
        int i = 0, internal_i = 0; 
        char[] arr = s.ToCharArray(); 
      
        while (i != arr.Length) { 
            char ch = arr[i]; 
            if (chars.ToLower().IndexOf(ch) == -1) { 
                arr[internal_i] = arr[i]; 
                internal_i ++; 
            } 
            i++; 
        }  
         s = new String(arr); 

        return s.Substring(0, internal_i); 
    } 
    static void Main()
    {
        String first = "c# programming language"; 
        String second = "rogb"; 
        
        String s = removeChars(second, first); 
        Console.WriteLine(s); 
    }
}


/*
run:

b

*/

 



answered Feb 5, 2019 by avibootz
0 votes
using System;
using System.Collections.Generic;
using System.Text;

public static class Program
{
    public static string RemoveCharacters(
        string source,
        string charactersToRemove)
    {
        var forbidden = new HashSet<char>(charactersToRemove);
        var result = new StringBuilder();

        foreach (char c in source)
        {
            if (!forbidden.Contains(c)) {
                result.Append(c);
            }
        }

        return result.ToString();
    }

    public static void Main()
    {
        string first = "programming language";
        string second = "rogy";

        Console.WriteLine(RemoveCharacters(second, first));
    }
}


/*
run:

y

*/

 



answered Oct 3 by avibootz
0 votes
using System;
using System.Collections.Generic;
using System.Linq;

public static class Program
{
    /// <summary>
    /// Removes all characters from <paramref name="source"/>
    /// that appear in <paramref name="charactersToRemove"/>.
    /// </summary>
    public static string RemoveCharacters(
        string source,
        string charactersToRemove)
    {
        var forbidden = new HashSet<char>(charactersToRemove);

        return new string(
            source
                .Where(c => !forbidden.Contains(c))
                .ToArray());
    }

    public static void Main()
    {
        string first = "programming language";
        string second = "rogy";

        string result = RemoveCharacters(second, first);

        Console.WriteLine($"First : \"{first}\"");
        Console.WriteLine($"Second: \"{second}\"");
        Console.WriteLine($"Result: \"{result}\"");
    }
}


/*
run:

First : "programming language"
Second: "rogy"
Result: "y"

*/

 



answered Oct 3 by avibootz

Related questions

...