首页 > 代码库 > [C#]清除字符串内空格

[C#]清除字符串内空格

关键代码:

        /// <summary>        /// 清除字符串内空格        /// </summary>        /// <param name="str">需要处理的字符串</param>        /// <returns>处理好后的字符串</returns>        public static string ExceptBlanks(this string str)        {            int _length = str.Length;            if (_length > 0)            {                StringBuilder _builder = new StringBuilder(_length);                for (int i = 0; i < str.Length; i++)                {                    char _c = str[i];                    //switch (_c)                    //{                    //    case ‘\r‘:                    //    case ‘\n‘:                    //    case ‘\t‘:                    //    case ‘ ‘:                    //        continue;                    //    default:                    //        _builder.Append(_c);                    //        break;                    //}                    if (!char.IsWhiteSpace(_c))                        _builder.Append(_c);                }                return _builder.ToString();            }            return str;        }

测试代码:

        [TestMethod()]        public void ExceptBlanksTest()        {            string str = @"20140901  11 22 33  "; // TODO: 初始化为适当的值            string expected = "20140901112233"; // TODO: 初始化为适当的值            string actual = StringToolV2.ExceptBlanks(str);            Assert.AreEqual(expected, actual);        }

<style type="text/css">.csharpcode, .csharpcode pre{ font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/}.csharpcode pre { margin: 0em; }.csharpcode .rem { color: #008000; }.csharpcode .kwrd { color: #0000ff; }.csharpcode .str { color: #006080; }.csharpcode .op { color: #0000c0; }.csharpcode .preproc { color: #cc6633; }.csharpcode .asp { background-color: #ffff00; }.csharpcode .html { color: #800000; }.csharpcode .attr { color: #ff0000; }.csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em;}.csharpcode .lnum { color: #606060; }</style>测试结果:

image

希望有所帮助!

[C#]清除字符串内空格