如何替换"在.NET中

Adr*_*ian 0 .net replace visual-studio

简单!如何在.NET中用某些东西替换?

Ste*_*tti 8

string result = myString.Replace("\"", "foo");
Run Code Online (Sandbox Code Playgroud)


Joh*_*her 5

string newValue = "quote \"here\"".Replace("\"", "'");
Run Code Online (Sandbox Code Playgroud)

或者

string newValue = @"quote ""here""".Replace(@"""", "'");
Run Code Online (Sandbox Code Playgroud)


Dan*_*Tao 5

哦,你的意思是你想用其他东西替换所有出现的字符串"

试试这个:

public static class EvilStringHelper {
    private static readonly Action<string, int, char> _setChar;
    private static readonly Action<string, int> _setLength;

    static EvilStringHelper() {
        MethodInfo setCharMethod = typeof(string).GetMethod(
            "SetChar",
            BindingFlags.Instance | BindingFlags.NonPublic
        );

        _setChar = (Action<string, int, char>)Delegate.CreateDelegate(typeof(Action<string, int, char>), setCharMethod);

        MethodInfo setLengthMethod = typeof(string).GetMethod(
            "SetLength",
            BindingFlags.Instance | BindingFlags.NonPublic
        );

        _setLength = (Action<string, int>)Delegate.CreateDelegate(typeof(Action<string, int>), setLengthMethod);
    }

    public static void ChangeTo(this string text, string value) {
        _setLength(text, value.Length);
        for (int i = 0; i < value.Length; ++i)
            text.SetChar(i, value[i]);
    }

    public static void SetChar(this string text, int index, char value) {
        _setChar(text, index, value);
    }
}
Run Code Online (Sandbox Code Playgroud)

用法:

"\"".ChangeTo("Bob");
string test = string.Concat("\"", "Hello!", "\"");
Console.WriteLine(test);
Run Code Online (Sandbox Code Playgroud)

输出:

BobHello!Bob

注意:这完全是个玩笑.