使用C#.NET进行字符串操作

使用C#.NET进行字符串操作,c#,.net,C#,.net,我需要c#中字符串操作的帮助 我有带单词的字符串,单词之间有空格(单词之间有多个空格,空格是动态的)。 我需要用破折号“-”替换空格 我有这样的想法: string stringForManipulation = "word1 word2 word3"; 我需要这个: "word1-word2-word3" Tnx您可以使用正则表达式: string stringForManipulation = "word1 word2 word3"; string result =

我需要c#中字符串操作的帮助

我有带单词的字符串,单词之间有空格(单词之间有多个空格,空格是动态的)。 我需要用破折号“-”替换空格

我有这样的想法:

string stringForManipulation  = "word1    word2  word3"; 
我需要这个:

"word1-word2-word3"

Tnx

您可以使用正则表达式:

string stringForManipulation = "word1    word2  word3";
string result = Regex.Replace(stringForManipulation, @"\s+", "-");
这将把所有出现的一个或多个空格替换为“-”


s
表示空白,
+
表示一次或多次出现。

对于那些不了解正则表达式的人,可以通过简单的拆分-联接操作来实现:

string wordsWithDashes = stringForManipulation.Split(new []{' '}, StringSplitOptions.RemoveEmptyEntries).Join('-')
简单使用

string result=Regex.Replace(str , @"\s+", "-")

将用单个“-”替换单个或多个空格

您可以尝试以下操作

string stringForManipulation  = "word1    word2  word3"; 
string wordsWithDashes  = String.Join(" ", stringForManipulation.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries)).Replace(" ", "-");

创建了一个

它可以。。。但这是一种罕见的情况,其中正则表达式是更好的答案,因为正则表达式解决方案更简单、更容易阅读。我同意正则表达式代码更短,但有许多人对编程一无所知,对正则表达式一无所知。@cyberj0g-…在这种情况下,他们肯定应该了解正则表达式是一种东西。我不相信你的解决方案对于编程新手来说更容易理解。此外,声明“没有正则表达式也可以做”是正确的,但请添加“为什么没有正则表达式也可以做”部分。这个问题是“给我代码”。在要求解决方案之前,先表明你已经尝试了一些东西。这是一个好的开始。谢谢!干杯
string stringForManipulation  = "word1    word2  word3"; 
string wordsWithDashes  = String.Join(" ", stringForManipulation.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries)).Replace(" ", "-");