Remove extra spaces from a string in C#

Problem source: http://www.geeksforgeeks.org/remove-extra-spaces-string/

The problem is to remove extra spaces from the string, from beginning of the string,
from end of the string and between words. But for special character like “.”, “,”, “?”
there should not be any space before them. Time complexity should be O(n).

Input: ”    Hi   ,   this is test string       input.   What do you think it’ll  work    ?    ”
Output: “Hi, this is test string input. What do you think it’ll  work?”

 class RemoveExtraSpacesFromAString
    {
        static void Main(string[] args)
        {
            string input = ”    Hi   ,   this is test string       input.   What do you think it’ll  work    ?    “;
            bool isPreviousCharSpace = false, isFirstCharFound = true;
            foreach (var ch in input)
            {
                if (ch != ‘ ‘)
                {
                    if (isPreviousCharSpace)
                    {
                        if (ch == ‘.’ || ch == ‘?’ || ch == ‘,’ || isFirstCharFound)
                        {
                            Console.Write(ch);
                        }
                        else
                        {
                            Console.Write(string.Concat(” “, ch));
                        }
                        isPreviousCharSpace = false;
                    }
                    else
                    {
                        Console.Write(ch);
                    }

                    isFirstCharFound = false;
                }
                else
                {
                    isPreviousCharSpace = true;
                }
            }
            Console.ReadKey();
        }
    }

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s