Replacing several different characters in a string

I am trying to replace several characters in some line 14/04/2010 17:12:11and get, for example, the following result:

14%04%2010%17%12%11

I know about the method Replace, but its definition looks like Replace(Char,Char). This means using 3 times in a chain of methods. Doesn't look idiomatic. How to solve the problem in the best way? Ordinary expressions? Any ways to avoid them?

+3
source share
4 answers

Chain:

string s1 = "14/04/2010 17:12:1";

string s2 = s1.Replace("/","%").Replace(" ","%").Replace(":","%");
+7
source
Regex.Replace(myString, "[/ :]", "%");

Simple but elegant!

+8
source

Regex, . :

string date2 = Regex.Replace(date1, @"\D", "%");
0

, :

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, "/ :", '%'));
0

Source: https://habr.com/ru/post/1742174/


All Articles