user48408
user48408

Reputation: 3354

Remove all instances of a character from string

I want to remove all instances of a character from a string except where that character is followed by any form or whitespace. I haven't written unit tests yet but it seems like the code below achieves what I want (possibly forgetting an edge case or two which is ok for now). It feels pretty clunky though. Can anyone suggest an improvement?

public string Strip(string text, char c)
{
    if (!string.IsNullOrEmpty(text))
    {
        bool characterIsInString = true;
        int currentIndex = 0;

        while (characterIsInString)
        {
            currentIndex = text.IndexOf(c, currentIndex + 1);

            if (currentIndex != -1)
            {
                var charAfter = text.Substring(currentIndex + 1, 1);

                if (charAfter != " ")
                {
                    text = text.Remove(currentIndex, 1);
                }
            }
            else
            {
                characterIsInString = false;
            }
        }
    }

    return text;
}

Upvotes: 0

Views: 2950

Answers (3)

Reza Jenabi
Reza Jenabi

Reputation: 4279

if you want replace character you can replace char with Replace method

Follow code:

Console.ReadLine().Replace("e","h");

Upvotes: 0

Poul Bak
Poul Bak

Reputation: 10929

I suggest, you use the following code:

public string Strip(string text, char c)
{
    Regex regex = new Regex(c.ToString() + @"[^\s]");
    return regex.Replace(text, "");
}

This will remove the char in text if it's not followed by a White Space.

This is a very simple and fast regex.

Upvotes: 1

Ashkan Mobayen Khiabani
Ashkan Mobayen Khiabani

Reputation: 34152

You can use Regular Expression( here i have assumed that character is x):

string result = Regex.Replace( input , "x(?=\\S)" , "");

Live Demo. Please check that it uses very few steps finding it.

Upvotes: 4

Related Questions