Remove ‘extra’ spaces in C # (C Sharp) string using recursion

This is a little code function that I developed to remove ‘extra’ spaces from a string.  I.e. removing any groups of two or more spaces.

Basic theory is to replace all pairs of spaces with a single space, and keep doing this until no pairs of spaces exist in the string (checking for pairs still returns true for three or more spaces as these contain a pair).

public static string RemoveExtraSpaces(string str)
{
    if (str.IndexOf("  ") == -1)
    {
        return str;
    }
    else
    {
        return RemoveExtraSpaces(str.Replace("  "," "));
    }
}
Advertisements
This entry was posted in Programming and tagged , , , . Bookmark the permalink.

2 Responses to Remove ‘extra’ spaces in C # (C Sharp) string using recursion

  1. zak says:

    while(str.contains(” “))
    str = str.replace(” “, ” “);

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