日期:2014-05-17  浏览次数:20846 次

C#字符串去中间空格

A方法一

static void Main(string[] args)
{
String str = "aa bb cc dd"; //需要处理的字符串
string[] s = str.Split(' '); //全部拆解
StringBuilder sb = new StringBuilder();
foreach (string item in s)
{
if (item.Trim() != "")
{
sb.Append(item); //把为空的字符串组合起来
sb.Append(" "); //并且追加一个空格
}
}
Console.WriteLine(sb);

Console.ReadLine();
}

B.

string strOriginal = "YY        YY";
            int firstSpace = strOriginal.IndexOf(" ");
            int lastSpace = strOriginal.LastIndexOf(" ");
            if (firstSpace != -1 && lastSpace != -1)
            {
                string subString = strOriginal.Remove(firstSpace + 1, lastSpace - firstSpace + 1);

                MessageBox.Show(subString);
            }

C.

string[] s=str.split(" "); //全部拆解
stringbuilder sb=new stringbuilder();
forech (string item in s)
{
if (s.trim()!="") sb.append(item)
}

retrun sb.tostring();

D

using System;
using System.Text.RegularExpressions;

class MyClass
{
static void Main(string[] args)
{
string sInput, sRegex;

sInput = "aa b c d e ";

sRegex = "[ ]+";

Regex r = new Regex(sRegex);

MyClass c = new MyClass();

// Assign the replace method to the MatchEvaluator delegate.
MatchEvaluator myEvaluator = new MatchEvaluator(c.ReplaceCC);

// Write out the original string.
Console.WriteLine(sInput);

// Replace matched characters using the delegate method.
sInput = r.Replace(sInput, myEvaluator);

// Write out the modified string.
Console.WriteLine(sInput);
}

public string ReplaceCC(Match m)
// Replace each Regex cc match with the number of the occurrence.
{
i++;
return " ";
}
public static int i = 0;
}