【问题标题】:Using a for loop to replace string characters in a .NET C# Model使用 for 循环替换 .NET C# 模型中的字符串字符
【发布时间】:2013-04-16 15:54:25
【问题描述】:

我是 .NET MVC 的新手,来自 PHP/Java/ActionScript。

我遇到的问题是 .NET 模型和get{}。我不明白为什么我的Hyphenize 字符串会返回截断为 64 个字符的SomeText 的值,但不会替换数组中定义的任何字符。

模型 - 这应该用简单的连字符 - 替换 SomeText 中的某些字符:

    public string SomeText{ get; set;} // Unmodified string

    public string Hyphenize{ 
        get {
            //unwanted characters to replace
            string[] replace_items = {"#", " ", "!", "?", "@", "*", ",", ".", "/", "'", @"\", "=" };
            string stringbuild = SomeText.Substring(0, (SomeText.Length > 64 ? 64 : SomeText.Length));

            for (int i = 0; i < replace_items.Length; i++)
            {
                stringbuild.Replace(replace_items[i], "-");
            }

            return stringbuild;
        }

        set { }
    }

或者,下面的方法确实可以正常工作,并将返回替换" ""#" 字符的字符串。但是,令我困扰的是,我无法理解为什么 for 循环不起作用。

    public string Hyphenize{ 
        get {
            //Replaces unwanted characters
            return SomeText.Substring(0, (SomeText.Length > 64 ? 64 : SomeText.Length)).Replace(" ", "-").Replace("#", "-");
        }

        set { }
    }

最终我得到了

return Regex.Replace(SomeText.Substring(0, (SomeText.Length > 64 ? 64 : SomeText.Length)).Replace("'", ""), @"[^a-zA-Z0-9]", "-").Replace("--", "-");

【问题讨论】:

    标签: c# asp.net-mvc variables


    【解决方案1】:

    string不可变的,来自MSDN

    字符串是不可变的——字符串对象的内容在对象创建后不能更改,尽管语法看起来好像您可以这样做。

    所以你需要重新分配:

     stringbuild = stringbuild.Replace(replace_items[i], "-");
    

    【讨论】:

      【解决方案2】:

      您没有将Replace() 的值分配给任何东西。它返回它的结果,并且不修改它所操作的字符串。 (字符串是不可变的)。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-11-28
        • 2017-04-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-01-17
        • 1970-01-01
        相关资源
        最近更新 更多