尝试用一个空格替换所有空格 [英] Trying to replace all white space with a single space

查看:56
本文介绍了尝试用一个空格替换所有空格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有什么想法吗?

我的程序是一个文件验证实用程序,我必须读入一个格式文件,然后用一个空格解析出每一行.但显然,编写格式文件的人可能会使用制表符、2 个空格或任何形式的空格,我正在寻找一些代码来做到这一点.我试过这个:

My program is a file validation utility and I have to read in a format file then parse out each line by a single space. But obviously, the person who wrote the format file may use tabs, or 2 spaces, or any form of whitespace, and I'm looking for some code to do that. I've tried this:

        public static string RemoveWhitespace(this string line) 
        {
            try 
            { 
                return new Regex(@"\s*").Replace(line, " "); 
            } 
            catch (Exception) 
            { 
                return line; 
            }
        }

我认为这是错误的.
帮助!

I'm assuming this is wrong.
Help!

推荐答案

你可以这样做 -

System.Text.RegularExpressions.Regex.Replace(str,@"\s+"," ");

其中 str 是您的字符串.

where str is your string.

这篇关于尝试用一个空格替换所有空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆