如何更快的删除String中的空格[未完]

背景:此文章主要源于网址[1]所描述的,文中大部分方法亦是[1]中实现的。

下面介绍集中删除空格的方法:

方法1:按空格分割后再拼接

 /// <summary>
        /// 按空格分割后拼接——Join
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string TrimAllWithSplitAndJoin(string str)
        {
            return string.Join("", str.Split(default(string[]), StringSplitOptions.RemoveEmptyEntries));
        }

        /// <summary>
        /// 按空格分割后拼接——Concat
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string TrimAllWithSplitAndConcat(string str)
        {
            return string.Concat(str.Split(default(string[]), StringSplitOptions.RemoveEmptyEntries));
        }

方法2:利用Linq一个一个字符拼接【注:[1]网址中对IsWhiteSpace还做了优化】

 /// <summary>
        /// 利用Linq一个一个字符拼接
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string TrimAllWithLinq(string str)
        {
            return new string(str.Where(c => !char.IsWhiteSpace(c)).ToArray());
        }

方法3:利用正则表达式替换空格为空字符——看起来比较高大上【注:[1]网址中将Regex的实例化放到了方法外以减少实例化时间】

/// <summary>
        /// 利用正则表达式替换空格为空字符
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string TrimAllWithRegex(string str)
        {
            Regex whitespace = new Regex(@"s+", RegexOptions.Compiled);
            return whitespace.Replace(str, "");
        }

方法4:自己实现使用字符数组一个一个拼接

/// <summary>
        /// 自己实现一个字符一个字符拼接
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string TrimAllWithCharArray(string str)
        {
            int len = str.Length;
            char[] strTochars = str.ToCharArray();
            int index = 0;
            for (int i = 0; i < len; i++)
            {
                char ch = strTochars[i];
                if (!char.IsWhiteSpace(ch))
                    strTochars[index++] = ch;
            }
            return new string(strTochars, 0, index);
        }

方法5:利用String自带方法Replace替换【注:[1]网址中提到了此法其实是有缺陷的】

 /// <summary>
        /// 使用String的Replace功能替换
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string TrimAllWithStringReplace(string str)
        {
            return str.Replace(" ", "");
        }

关于性能测试准备使用老赵的CodeTimer。

相关网址:

原文地址:https://www.cnblogs.com/huaxia283611/p/trimstringspacefaster.html