从字符串中删除字符的所有实例

问题描述 投票:0回答:3

我想从字符串中删除字符的所有实例,除非该字符后跟任何形式或空格。我还没有编写单元测试,但似乎下面的代码实现了我想要的东西(可能忘记了一两个边缘情况,现在还可以)。虽然感觉很笨重。有人可以提出改进吗?

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;
}
c# regex string
3个回答
4
投票

你可以使用正则表达式(这里我假设字符是x):

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

Live Demo。请检查它是否只使用了很少的步骤。


1
投票

我建议你使用以下代码:

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

这将删除char中的text,如果它是not,然后是白色Space

这是一个非常简单快速的正则表达式。


0
投票

如果你想要替换字符,你可以用Replace方法替换char

关注代码:

Console.ReadLine().Replace("e","h");
© www.soinside.com 2019 - 2024. All rights reserved.