2
\$\begingroup\$

I have a string of Hebrew text which also contains":", "-", & "|". Attempting to replace "-", "|", and ":" with a space. How can I do this efficiently?

string my_string = "עַל־פְּנֵי:על־פני|על־פני";
string[] replace_chars = new string[] {":","-","|"};
foreach (string char_change in replace_chars){
    if(char_change == ":" || char_change == "-" || char_change == "|"){
       my_string = my_string.Replace(char_change, " ");
    }
}
\$\endgroup\$
3
  • \$\begingroup\$ Is there any alternative to have this done ? \$\endgroup\$ Oct 12, 2021 at 19:54
  • \$\begingroup\$ You can look at this stackoverflow question stackoverflow.com/q/7265315. Pretty much covers all the options. from regex to string split to linq \$\endgroup\$ Oct 12, 2021 at 20:46
  • \$\begingroup\$ Your code does not follow the Microsoft guidelines: docs.microsoft.com/en-us/dotnet/standard/design-guidelines/… : "DO NOT use underscores, hyphens, or any other nonalphanumeric characters." Also, you use the word "char" when in reality it is a string. \$\endgroup\$
    – BCdotWEB
    Oct 13, 2021 at 6:34

1 Answer 1

4
\$\begingroup\$

you can always use Replace extension, it's fast, durable, and under your hands. So, your work would be something like :

const char space = '\u0020'; // for readability purpose.

var result = my_string.Replace(':', space).Replace('-', space).Replace('|', space);

or if you have larger strings or you think it would be executed repeatedly, you can always use StringBuilder.

const char space = '\u0020'; // for readability purpose.

var builder = new StringBuilder(my_string);

var result = builder
    .Replace(':', space)
    .Replace('-', space)
    .Replace('|', space)
    .ToString();
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.