首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > .NET > C# >

string.Trim(char[])函数没起任何作用,为什么

2013-09-06 
string.Trim(char[])函数没有起任何作用,为什么?下面这一段程序:string s abcesdf char[] sz {

string.Trim(char[])函数没有起任何作用,为什么?
下面这一段程序:


            string s = " abc   esdf ";
            char[] sz = { ' ', 'e' };
            string snew = s.Trim(sz);
            Console.WriteLine(snew+","+s);
           

运行输出的结果是:
abc   esdf, abc   esdf
为什么没有如我预期的那样去掉空格呢?

[解决办法]
Trim()函数就是删除文字列开头和末尾的

中间的不能删除 用 replace吧


string s = " eabc   esdfe ";            
char[] sz = { ' ', 'e' };            
string snew = s.Trim(sz);            
Console.WriteLine(snew+","+s);

[解决办法]
like this:
string s = " abc   esdf ";
            char[] sz = { ' ', 'e' };
            string[] snew = s.Split(sz, StringSplitOptions.RemoveEmptyEntries);
            foreach (string item in snew)
            {
                Console.WriteLine(item);
            }

[解决办法]
Trim是去掉开头和结尾的空格
用正则

  string s = " abc   esdf ";


            char[] sz = { ' ', 'e' };
            string snew = System.Text.RegularExpressions.Regex.Replace(s,@"[\se]*","");
            Console.WriteLine(snew);

热点排行