Reputation: 3214
I try to replace few characters in some string 14/04/2010 17:12:11
and get, for example, next result:
14%04%2010%17%12%11
I know about method Replace
, but its definition looks like Replace(Char,Char)
. Which means using it 3 times in method chain. Doesn't look idiomatic. How to solve the problem in an optimal way? Regular expressions? Any ways to escape them?
Upvotes: 4
Views: 2933
Reputation: 171351
An alternate Regex
approach, although I disagree with the use of it here. This simply replaces any non-numeric characters:
string date2 = Regex.Replace(date1, @"\D", "%");
Upvotes: 0
Reputation: 16747
If you have to do it often, write a method:
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;
}
e.g.
string s1 = "14/04/2010 17:12:11";
string s2 = Replace(s1, "/ :", '%'));
Upvotes: 0
Reputation: 81429
Chain it:
string s1 = "14/04/2010 17:12:1";
string s2 = s1.Replace("/","%").Replace(" ","%").Replace(":","%");
Upvotes: 8