Method string.Replace( ) doesn't work

2019-02-27 13:34发布

    public string Generate()
    {
        RandomNumberGenerator rdng = new RNGCryptoServiceProvider();
        byte[] bytes = new byte[40];

        rdng.GetBytes(bytes);

        string a = Convert.ToBase64String(bytes); 

        a.Replace("=", "r");
        a.Replace("+", "t");

        return a;
    }

a=43TvtRvrTrt54g5gtbrTTBR45iu+zqbB03gXej== ;

after a.Replace() again:

a=43TvtRvrTrt54g5gtbrTTBR45iu+zqbB03gXej== ;

I want to generate unique value in my C# project. Everything is great. But When I want to call string.Replace(), it doesn't work. Values after and before this method are the same. Why ?

标签: c# string random
4条回答
女痞
2楼-- · 2019-02-27 13:36

String.Replace is not modifying a, but returning a new String. As this makes it chainable, a solution could look like:

a = a.Replace("=", "r").Replace("+", "t");
查看更多
SAY GOODBYE
3楼-- · 2019-02-27 13:38

The replace method returns a new string object, it does not modify the existing string. The following statement should work:

a = a.Replace("=", "r");
查看更多
男人必须洒脱
4楼-- · 2019-02-27 13:51

It works. It just doesn't do what you think: it doesn't edit the existing string: it creates a new string. Try:

    a = a.Replace("=", "r");
    a = a.Replace("+", "t");

This is because strings are immutable: they do not change once created (at least, not if you might be looking - there are some exceptions like the internals of StringBuilder, but those are implementation details that you shouldn't see)

查看更多
女痞
5楼-- · 2019-02-27 13:52

The problem is that the method doesn't change the string you call the method on, but returns another occurrence of the string, so you should assign it to another object in order for the changes to persist because a string is a non mutable object:

a=a.Replace("=", "r");
a=a.Replace("+", "t");
查看更多
登录 后发表回答