需要从文本文件中逐行读取数据。多数情况下读取出的数据中包含重复的空格,如:“张三    30    男    汉族”,需要转换成“张三 30 男 汉族”的形式以进行下面的操作。请教是否有高效的方法?

解决方案 »

  1.   

                string s = "a   b c";
                string[] x = s.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
                string y = string.Join(" ", x);
      

  2.   

    replace("  "," ")
    试试这个?把两个空格替换成1个空格。
      

  3.   

    string test = "张三    30    男     汉  族";
    test = System.Text.RegularExpressions.Regex.Replace(test, @"[  ]+", " ");
      

  4.   

    试试这个\s代表空格或者Tab之类的分隔符,有两个或者两个以上就替换为一个空格
    [code]
    string test = "张三    30    男     汉  族";
    test = System.Text.RegularExpressions.Regex.Replace(test, @"\s{2,}", " ");
    [/code]
      

  5.   

    2楼的不错
    string s = "a   b c";
                string[] x = s.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
                string y = string.Join(" ", x);但是9,11楼的也行啊
    replace("  "," ") 
    试试这个?把两个空格替换成1个空格。string test = "张三    30    男     汉  族";
    test = System.Text.RegularExpressions.Regex.Replace(test, @"[  ]+", " ");
    楼主去选择吧
      

  6.   

    string test = "张三    30    男     汉  族";
            string s = Regex.Replace(test, @"\s", string.Empty);
            Response.Write(s);
      

  7.   

    //高  实在是高   二楼 我爱你
    //高  实在是高   二楼 我爱你
    //高  实在是高   二楼 我爱你
    //高  实在是高   二楼 我爱你
    string s = "a  b c"; 
                string[] x = s.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); 
                string y = string.Join(" ", x); 
      

  8.   


    string test = "张三    30    男     汉  族";
    string s = Regex.Replace(test, @"\s", " ");
      

  9.   


    string test = "张三    30    男     汉  族";
    string s = Regex.Replace(test, @"\s{2,}", " ");
      

  10.   

    哦另外,直接Replace("  ", " ")能将两个空格变成一个,但是似乎对于三、四个空格的情况似乎还是会有连续的空格,所以恐怕直接Replace比较困难,至少可能需要做个循环什么的。