I\'m trying to fetch multiple email addresses seperated by \",\" within string from database table, but it\'s also returning me whitespaces, and I want to remove the whitesp
With linq you can do it simply:
emailaddress = new String(emailaddress
.Where(x=>x!=' ' && x!='\r' && x!='\n')
.ToArray());
I didn't compare it with stringbuilder approaches, but is much more faster than string based approaches. Because it does not create many copy of strings (string is immutable and using it directly causes to dramatically memory and speed problems), so it's not going to use very big memory and not going to slow down the speed (except one extra pass through the string at first).
Fastest and general way to do this (line terminators, tabs will be processed as well). Regex powerful facilities don't really needed to solve this problem, but Regex can decrease performance.
new string
(stringToRemoveWhiteSpaces
.Where
(
c => !char.IsWhiteSpace(c)
)
.ToArray<char>()
)
You should try String.Trim()
. It will trim all spaces from start to end of a string
Or you can try this method from linked topic: [link]
public static unsafe string StripTabsAndNewlines(string s)
{
int len = s.Length;
char* newChars = stackalloc char[len];
char* currentChar = newChars;
for (int i = 0; i < len; ++i)
{
char c = s[i];
switch (c)
{
case '\r':
case '\n':
case '\t':
continue;
default:
*currentChar++ = c;
break;
}
}
return new string(newChars, 0, (int)(currentChar - newChars));
}
Given the implementation of string.Replace
is written in C++ and part of the CLR runtime I'm willing to bet
email.Replace(" ","").Replace("\t","").Replace("\n","").Replace("\r","");
will be the fastest implementation. If you need every type of whitespace, you can supply the hex value the of unicode equivalent.
Please use the TrimEnd()
method of the String
class. You can find a great example here.
string str = "Hi!! this is a bunch of text with spaces";
MessageBox.Show(new String(str.Where(c => c != ' ').ToArray()));