最快去除字符串空格的方式 [英] Fastest way to remove white spaces in string
问题描述
我想取内数据库表中的字符串由分隔,多个电子邮件地址,但它也回到了我的空格,我想快速去除空白。
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 whitespace quickly.
下面code不删除空白,但它也变得缓慢每当我试图取像到30000字符串大量电子邮件地址,并尝试消除它们之间的空白。它需要超过四到五分钟以去除这些空间。
The following code does remove whitespace, but it also becomes slow whenever I try to fetch large number email addresses in a string like to 30000, and then try to remove whitespace between them. It takes more than four to five minutes to remove those spaces.
Regex Spaces =
new Regex(@"\s+", RegexOptions.Compiled);
txtEmailID.Text = MultipleSpaces.Replace(emailaddress),"");
谁能告诉我怎样才能删除空格内的第二甚至是大量电子邮件地址?
Could anyone please tell me how can I remove the whitespace within a second even for large number of email address?
推荐答案
我会用建立一个自定义的扩展方法的StringBuilder
,如:
I would build a custom extension method using StringBuilder
, like:
public static string ExceptChars(this string str, IEnumerable<char> toExclude)
{
StringBuilder sb = new StringBuilder(str.Length);
for (int i = 0; i < str.Length; i++)
{
char c = str[i];
if (!toExclude.Contains(c))
sb.Append(c);
}
return sb.ToString();
}
用法:
var str = s.ExceptChars(new[] { ' ', '\t', '\n', '\r' });
或更快的速度:
or to be even faster:
var str = s.ExceptChars(new HashSet<char>(new[] { ' ', '\t', '\n', '\r' }));
随着HashSet的版本中,1100万字符的字符串只需要不到700毫秒(我在调试模式下)
With the hashset version, a string of 11 millions of chars takes less than 700 ms (and I'm in debug mode)
编辑:
previous code是通用的,可以排除任何字符,但如果要删除只是空白的,你可以用最快的方式:
Previous code is generic and allows to exclude any char, but if you want to remove just blanks in the fastest possible way you can use:
public static string ExceptBlanks(this string str)
{
StringBuilder sb = new StringBuilder(str.Length);
for (int i = 0; i < 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();
}
编辑2:
作为正确地指出了意见,正确的方法去除的所有的空白使用 char.IsWhiteSpace
方法:
as correctly pointed out in the comments, the correct way to remove all the blanks is using char.IsWhiteSpace
method :
public static string ExceptBlanks(this string str)
{
StringBuilder sb = new StringBuilder(str.Length);
for (int i = 0; i < str.Length; i++)
{
char c = str[i];
if(!char.IsWhiteSpace(c))
sb.Append(c);
}
return sb.ToString();
}
这篇关于最快去除字符串空格的方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!