我是.NET MVC的新手,来自PHP/Java/ActionScript。使用for循环替换.NET C#模型中的字符串字符
我遇到的问题是.NET模型和get{}
。我不明白为什么我的Hyphenize
字符串将返回值SomeText
截断为64个字符,但不替换数组中定义的任何字符。
模式 - 这应该用一个简单的连字符-
替换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("--", "-");