我尝试替换一些字符串中的字符 14/04/2010 17:12:11
,并获得如下结果:
14%04%2010%17%12%11
我知道关于方法
Replace
,但它的定义看起来像是Replace(Char,Char)
。这意味着在方法链中要使用3次。看起来不太符合惯用方式。有什么最优解决方案吗?正则表达式?有任何转义方法吗?Regex.Replace(myString, "[/ :]", "%");
简单,却优雅!
string s1 = "14/04/2010 17:12:1";
string s2 = s1.Replace("/","%").Replace(" ","%").Replace(":","%");
如果你需要经常这么做,编写一个方法:
static string Replace(string s, string c, char n)
{
for (int i = 0; i < c.Length; i++)
s = s.Replace(c[i], n);
return s;
}
例如
string s1 = "14/04/2010 17:12:11";
string s2 = Replace(s1, "/ :", '%'));
string date2 = Regex.Replace(date1, @"\D", "%");
Replace
也可以像这样作为构造函数:Replace(String, String)
。 - D'Arcy Rittich