c# - Fastest way to remove white spaces in string -


i'm trying fetch multiple email addresses seperated "," within string database table, it's returning me whitespaces, , want remove whitespace quickly.

the following code remove whitespace, becomes slow whenever try fetch large number email addresses in string 30000, , try remove whitespace between them. takes more 4 5 minutes remove spaces.

 regex spaces =         new regex(@"\s+", regexoptions.compiled); txtemailid.text = multiplespaces.replace(emailaddress),""); 

could please tell me how can remove whitespace within second large number of email address?

i build custom extension method using stringbuilder, like:

public static string exceptchars(this string str, ienumerable<char> toexclude) {     stringbuilder sb = new stringbuilder(str.length);     (int = 0; < str.length; i++)     {         char c = str[i];         if (!toexclude.contains(c))             sb.append(c);     }     return sb.tostring(); } 

usage:

var str = s.exceptchars(new[] { ' ', '\t', '\n', '\r' }); 

or faster:

var str = s.exceptchars(new hashset<char>(new[] { ' ', '\t', '\n', '\r' })); 

with hashset version, string of 11 millions of chars takes less 700 ms (and i'm in debug mode)

edit :

previous code generic , allows exclude char, if want remove blanks in fastest possible way can use:

public static string exceptblanks(this string str) {     stringbuilder sb = new stringbuilder(str.length);     (int = 0; < str.length; i++)     {         char c = str[i];         switch (c)         {             case '\r':             case '\n':             case '\t':             case ' ':                 continue;             default:                 sb.append(c);                 break;         }     }     return sb.tostring(); } 

edit 2 :

as correctly pointed out in comments, correct way remove all blanks using char.iswhitespace method :

public static string exceptblanks(this string str) {     stringbuilder sb = new stringbuilder(str.length);     (int = 0; < str.length; i++)     {         char c = str[i];         if(!char.iswhitespace(c))             sb.append(c);     }     return sb.tostring(); } 

Comments

Popular posts from this blog

c# - How to set Z index when using WPF DrawingContext? -

razor - Is this a bug in WebMatrix PageData? -

visual c++ - Using relative values in array sorting ( asm ) -