A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© Kaitong 中级黑马   /  2014-4-2 20:04  /  1367 人查看  /  6 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

本帖最后由 Kaitong 于 2014-4-3 09:23 编辑

/* 将字符串"  hello      world,你  好 世界   !    " 的两端的空格去掉, 并且将其中的所有其他空格都替换成一个空格,
最终输出结果为:"hello world,你 好 世界 !"。*/
  1. string hello = "  hello      world,你  好 世界   !    ";//原字符串           
  2.             hello = hello.Trim();//去掉两端空格  
复制代码

我就会去掉两端的空格,中间的双重空格怎么换成单空格啊?谢谢

评分

参与人数 1技术分 +1 收起 理由
czwanglei + 1

查看全部评分

6 个回复

倒序浏览
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace 字符串中多余空格
{
    class Program
    {
        static void Main(string[] args)
        {
            string hello = "  hello      world,你  好 世界   !    ";//原字符串           
            string[] strs = (hello.Trim()).Split(' ');
            List<string> strList = new List<string>();
            foreach (string str in strs)
            {
                if (str!="")
                {
                    strList.Add(str);
                }
            }
            Console.WriteLine(string.Join(" ", strList));
            
            Console.ReadKey();
        }
    }
}


评分

参与人数 1技术分 +1 收起 理由
czwanglei + 1

查看全部评分

回复 使用道具 举报
  1. string he = "  hello      world,你  好 世界   !    ";
  2.             Regex regex = new Regex(@"( )+");
  3.             Console.WriteLine(regex.Replace(he.Trim()," "));
复制代码
回复 使用道具 举报
//删除所所给字符中所有的空格
//Replace方法的两个参数支持使用正则表达式
string he = "  hello      world,你  好 世界   !    ";
Console.WriteLine(he.Replace(" ",""));

评分

参与人数 1技术分 +1 收起 理由
czwanglei + 1 赞一个!

查看全部评分

回复 使用道具 举报
可以结合string的Trim()与Replace() 这两个方法,trim就是去除字符串两端的空格但不能去除中间空格。
replace则是用一指定字符串去替代目标字符串中符合条件的部分
回复 使用道具 举报
本帖最后由 李恒权 于 2014-4-3 00:52 编辑

亲,给你个容易理解的且符合你的要求的。
  1.     string str = "  hello      world,你  好 世界   !    ";
  2.             string str1 = str.Trim();
  3.             //恰到好处的运用标志位
  4.             char fuhao = '@';
  5.             for (int i = 0; i < str1.Length; i++)
  6.             {
  7.                 //运用检索每一个字符
  8.                 char ch = str1.ElementAt(i);
  9.                 if (ch != ' ')
  10.                 {
  11.                     fuhao = '@';
  12.                     Console.Write(ch);
  13.                 }
  14.                 else
  15.                 {
  16.                     if (ch!=fuhao )
  17.                     {
  18.                         Console.Write(ch);
  19.                     }
  20.                     fuhao = ch;
  21.                 }
  22.             }
  23.            Console.ReadKey();
  24.            
复制代码

评分

参与人数 1技术分 +1 收起 理由
czwanglei + 1

查看全部评分

回复 使用道具 举报
李恒权 发表于 2014-4-3 00:50
亲,给你个容易理解的且符合你的要求的。

谢谢,我试试
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马