如何在C#中只用一个空格替换字符串中的多个空格?
示例:
PLNICI PERO 2165/HORNET SPACESPACESPACESPACESPACE
将是:
PLNICI PERO 2165/HORNET
第二名:
示例:
SPACESPACESPACESPACESPACE 77.000
将是:
77.000
请问您有什么想法吗?感谢
答案 0 :(得分:3)
string input = "you string ";
string result = new Regex(@"[ ]+").Replace(input, " ").Trim();
答案 1 :(得分:1)
using System;
using System.Text;
using System.Text.RegularExpressions; // for Regex
namespace tentitive
{
class Program
{
static void Main(string[] args)
{
string firstString = "PLNICI PERO 2165/HORNET ";
string secondString = " 77.000";
string toBeReplaced = "[ ]+"; // pattern to be replaced i.e. one or more occurences of white spaces
string replacer = " "; // has to be replaced with only One white space
string neededFirstString = Regex.Replace(firstString, toBeReplaced, replacer).ToString();
string neededSecondString = Regex.Replace(secondString, toBeReplaced, replacer).ToString();
Console.WriteLine(neededFirstString);
Console.WriteLine(neededSecondString);
Console.ReadLine();
}
}
}