从字符串中删除已定义的部分

Rnf*_*nft 2 c# string char

可以说我有这个字符串:

string text = "Hi my name is <crazy> Bob";
Run Code Online (Sandbox Code Playgroud)

我想带走括号内的所有内容,结果如下:

"Hi my name is Bob". 
Run Code Online (Sandbox Code Playgroud)

因此,我已经尝试过这个,我知道我一直认为while循环错了,但我无法理解.

    public static string Remove(string text)
    {
        char[] result = new char[text.Length];

        for (int i = 0; i < text.Length; i++ )
        {
            if (text[i] == '<')
            {
                while (text[i] != '>')
                {
                    result[i] += text[i];
                }
            }
            else
            {
                result[i] += text[i];
            }
        }
        return result.ToString();
    }
Run Code Online (Sandbox Code Playgroud)

Sri*_*vel 11

试试这个正则表达式:

public static string Remove(string text)
{
    return  Regex.Replace(text, "<.*?>","");
}
Run Code Online (Sandbox Code Playgroud)

  • 这是一个很好的选择,但它无法帮助OP理解为什么他们尝试的解决方案不起作用. (2认同)

Jon*_*eet 6

看看这个循环:

while (text[i] != '>')
{
    result[i] += text[i];
}
Run Code Online (Sandbox Code Playgroud)

这将继续执行,直到不满足条件.鉴于你没有改变text[i],它永远不会停止......

此外,你正在呼唤ToString一个char[]不会做你想要的东西,即使它确实你有剩下的角色.

如果你想像这样循环,我会使用a StringBuilder,并且只是跟踪你是否"在"一个尖括号中:

public static string RemoveAngleBracketedContent(string text)
{
    var builder = new StringBuilder();
    int depth = 0;
    foreach (var character in text)
    {
        if (character == '<')
        {
            depth++;
        }
        else if (character == '>' && depth > 0)
        {
            depth--;
        }
        else if (depth == 0)
        {
            builder.Append(character);
        }
    }
    return builder.ToString();
}
Run Code Online (Sandbox Code Playgroud)

或者,使用正则表达式.让它来应对嵌套的尖括号会相对棘手,但如果你不需要它,那很简单:

// You can reuse this every time
private static Regex AngleBracketPattern = new Regex("<[^>]*>");
...

text = AngleBracketPattern.Replace(text, "");
Run Code Online (Sandbox Code Playgroud)

最后一个问题 - 从"Hi my name is <crazy> Bob"你实际上取下角度括号文本后"Hi my name is Bob"- 注意双倍空间.