代码之家  ›  专栏  ›  技术社区  ›  user48408

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

  •  0
  • user48408  · 技术社区  · 6 年前

    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;
    }
    
    3 回复  |  直到 6 年前
        1
  •  4
  •   Ashkan Mobayen Khiabani    6 年前

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

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

    Live Demo . 请检查它是否使用很少的步骤找到它。

        2
  •  1
  •   Poul Bak    6 年前

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

    这将删除 char 在里面 text not 接着是一个白色的 Space .

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

        3
  •  0
  •   Reza Jenabi    6 年前

    可以将char替换为 Replace 方法

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