string str="测试 测试1 测试2 测试3 "string str1="test01 test002 test003 test004"如何去掉中间的空格使之变成 "测试 测试1 测试2 测试3"
"test001 test002 test003 test004"
中间只有个一个空格
"test001 test002 test003 test004"
中间只有个一个空格
string Cut(string str)
{
while(str.IndexOf(" ")!=-1)
{
str=str.Replace(" ", " ");
}
}
大意就是重复把两个空格替换成一个空格。
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;namespace CSharpTest
{
class Program
{
static void Main(string[] args)
{
string str = "测试 测试1 测试2 测试3 "; string str1 = "test01 test002 test003 test004";
Console.WriteLine(RemoveSpace(str));
Console.WriteLine(RemoveSpace(str1));
}
static string RemoveSpace(string str)
{
string result = Regex.Replace(str, @"[ ]+", " ");
return result;
}
}
}
string Cut(string str)
{
while(str.IndexOf(" ")!=-1)
{
str=str.Replace(" ", " ");
}
return str;
}
static string RemoveSpace(string str)
{
return Regex.Replace(str, " +", " ");
}
楼主结贴吧,如果sohighthesky兄弟不能完美解决你的问题的话,那么你应该不懂效率了。正则高效
string str="测试 测试1 测试2 测试3 ";
string str1 = "test01 test002 test003 test004";
str = System.Text.RegularExpressions.Regex.Replace(str1.Trim(), @"\s+", " ");
public string Trim(string str)
{
StringBuilder buf = new StringBuilder();
string[] temp = str.Split(new string[]{" "},StringSplitOptions.RemoveEmptyEntries); foreach (string item in temp)
{
buf.Append(item + " ");
} return buf.ToString().Trim();
}
string str = "测试 测试1 测试2 测试3 ";
textBox2.Text = Regex.Replace(str, " +", " ");
{
return Regex.Replace(source, @"[\p{Z}]+", " ");//\p{Z}在正则表达式里指代分隔符,空白
}