Tuesday, July 31, 2018

Algorithm to Remove character from string

Remove char from String :- Consider the requirement to strip invalid characters from a string. The characters just need to be removed and replace with blank or string.Empty.

Using Array

private static void RemoveCharFromStr(string source, char chr)
        {
            var pool = new char[source.Length];
            int poolCount = 0;
            for (int i = 0; i < source.Length; i++)
            {
                if (source[i] != chr)
                {
                    pool[poolCount] = source[i];
                    poolCount++;
                }
            }
            Console.WriteLine(new string(pool));
        }


Using Replace

source.Replace(str, string.Empty)


RemoveCharFromFirstStr :-

 private static void RemoveCharFromFirstStr()
        {
            string first = "char";
            string second = "Remove char from";

            var pool = new char[first.Length];
            int count = 0;
            for (int i = 0; i <first.Length; i++)
            {
                bool isfound = false;
                foreach (var c in second)
                {
                    if (first[i] == c)
                    {
                        isfound = true;
                        break;
                    }
                }
                if (!isfound)
                {
                    pool[count] = first[i];
                    count++;
                }
            }
            Console.WriteLine(new string(pool));

        }


No comments:

Post a Comment

Kafka setup in window

Here's a step-by-step guide on how to do it : 1. Prerequisites : Before you begin, make sure you have the following prerequisites inst...