![]() |
Replace multiple characters in a C# string - Printable Version +- 0Day Forums (https://0day.red) +-- Forum: Coding (https://0day.red/Forum-Coding) +--- Forum: C# (https://0day.red/Forum-C) +--- Thread: Replace multiple characters in a C# string (/Thread-Replace-multiple-characters-in-a-C-string) |
Replace multiple characters in a C# string - rosalinarosalind223 - 07-24-2023 Is there a better way to replace strings? I am surprised that Replace does not take in a character array or string array. I guess that I could write my own extension but I was curious if there is a better built in way to do the following? Notice the last Replace is a string not a character. myString.Replace(';', '\n').Replace(',', '\n').Replace('\r', '\n').Replace('\t', '\n').Replace(' ', '\n').Replace("\n\n", "\n"); RE: Replace multiple characters in a C# string - alchemy937 - 07-24-2023 You can use a replace regular expression. s/[;,\t\r ]|[\n]{2}/\n/g - `s/` at the beginning means a search - The characters between `[` and `]` are the characters to search for (in any order) - The second `/` delimits the search-for text and the replace text In English, this reads: "Search for `;` or `,` or `\t` or `\r` or ` ` (space) or exactly two sequential `\n` and replace it with `\n`" In C#, you could do the following: (after importing `System.Text.RegularExpressions`) Regex pattern = new Regex("[;,\t\r ]|[\n]{2}"); pattern.Replace(myString, "\n"); RE: Replace multiple characters in a C# string - copyist669 - 07-24-2023 If you are feeling particularly clever and don't want to use Regex: char[] separators = new char[]{' ',';',',','\r','\t','\n'}; string s = "this;is,\ra\t\n\n\ntest"; string[] temp = s.Split(separators, StringSplitOptions.RemoveEmptyEntries); s = String.Join("\n", temp); You could wrap this in an extension method with little effort as well. Edit: Or just wait 2 minutes and I'll end up writing it anyway :) public static class ExtensionMethods { public static string Replace(this string s, char[] separators, string newVal) { string[] temp; temp = s.Split(separators, StringSplitOptions.RemoveEmptyEntries); return String.Join( newVal, temp ); } } And voila... char[] separators = new char[]{' ',';',',','\r','\t','\n'}; string s = "this;is,\ra\t\n\n\ntest"; s = s.Replace(separators, "\n"); RE: Replace multiple characters in a C# string - bulginess165594 - 07-24-2023 This is the shortest way: myString = Regex.Replace(myString, @"[;,\t\r ]|[\n]{2}", "\n"); RE: Replace multiple characters in a C# string - wood378 - 07-24-2023 Ohhh, the performance horror! The answer is a bit outdated, but still... public static class StringUtils { #region Private members [ThreadStatic] private static StringBuilder m_ReplaceSB; private static StringBuilder GetReplaceSB(int capacity) { var result = m_ReplaceSB; if (null == result) { result = new StringBuilder(capacity); m_ReplaceSB = result; } else { result.Clear(); result.EnsureCapacity(capacity); } return result; } public static string ReplaceAny(this string s, char replaceWith, params char[] chars) { if (null == chars) return s; if (null == s) return null; StringBuilder sb = null; for (int i = 0, count = s.Length; i < count; i++) { var temp = s[i]; var replace = false; for (int j = 0, cc = chars.Length; j < cc; j++) if (temp == chars[j]) { if (null == sb) { sb = GetReplaceSB(count); if (i > 0) sb.Append(s, 0, i); } replace = true; break; } if (replace) sb.Append(replaceWith); else if (null != sb) sb.Append(temp); } return null == sb ? s : sb.ToString(); } } RE: Replace multiple characters in a C# string - Mramylenes853 - 07-24-2023 Performance-Wise this probably might not be the best solution but it works. var str = "filename:with&bad$separators.txt"; char[] charArray = new char[] { '#', '%', '&', '{', '}', '\\', '<', '>', '*', '?', '/', ' ', '$', '!', '\'', '"', ':', '@' }; foreach (var singleChar in charArray) { str = str.Replace(singleChar, '_'); } |