我是.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("--", "-");