我有以下挑战.我需要用一个数字替换字符串中的每个空格,该数字表示有多少空格.例如:"Hello World!"; 应修改为"Hello1World2!"; 我如何在c#中实现这一目标.请帮忙
我终于得到了一个正则表达式的答案:使用MatchEvaluator正则表达式的-class:
using System.Text.RegularExpressions;
static void Main(string[] args)
{
string input = "bla absl ael dls ale ";
var result2 = Regex.Replace(input, "\s+", new MatchEvaluator(ReplaceByCount));
Console.WriteLine(result2);
//returns bla1absl1ael3dls1ale1
}
private static string ReplaceByCount(Match m)
{
return m.Value.Length.ToString();
}
Run Code Online (Sandbox Code Playgroud)
编辑:用"\ s +"替换"+"以匹配@ Marco-Forbergs评论后的所有空格字符