C# 如何删除字符串中特定字符之间的空白?

C# 如何删除字符串中特定字符之间的空白?,c#,string,C#,String,所以我有一个这样的字符串: string sampleString = "this - is a string - with hyphens - in it"; 这里需要注意的是,在连字符的左侧和右侧有随机数目的空格。目标是用连字符替换字符串中的空格(因此字符串中的hypens会出现问题)。所以我想要的结果应该是这样的: string sampleString = "this - is a string - with hyphens - in it"; “这是一个

所以我有一个这样的字符串:

string sampleString = "this - is a string   - with hyphens  -     in it";
这里需要注意的是,在连字符的左侧和右侧有随机数目的空格。目标是用连字符替换字符串中的空格(因此字符串中的hypens会出现问题)。所以我想要的结果应该是这样的:

string sampleString = "this - is a string   - with hyphens  -     in it";
“这是一个带连字符的字符串”

目前我正在使用:

sampleString.Trim().ToLower().Replace(" ", "-")
但这会产生以下输出:

“这是一个带连字符的字符串”

寻找最干净、最简洁的解决方案


谢谢

只需一行就可以做到这一点

Regex.Replace(sampleString, @"\s+", " ").Replace (" ", "-");

尝试使用
System.Text.RegularExpressions.Regex

只要打电话:

Regex.Replace(sampleString, @"\s+-?\s*", "-");
试试这个:

private static readonly Regex rxInternaWhitespace = new Regex( @"\s+" ) ;
private static readonly Regex rxLeadingTrailingWhitespace = new Regex(@"(^\s+|\s+$)") ;
public static string Hyphenate( this string s )
{
  s = rxInternalWhitespace.Replace( s , "-" ) ;
  s = rxLeadingTrailingWhitespace.Replace( s , "" ) ;
  return s ;
}

如果您想要所有的单词和现有的hypens,那么另一种方法是将字符串拆分为一个数组,并在空格上进行分隔。然后重新生成字符串,忽略任何空格,同时插入连字符是合适的。

这看起来像是正则表达式(或者标记化,如果您愿意的话)

使用正则表达式,可以将所有空格和连字符拼凑起来,并用一个连字符替换。此表达式匹配任意数量的空格和连字符:

[- ]+
或者,您可以通过空格将字符串拆分为标记,然后在标记之间使用连字符重新组合字符串,除非标记本身是连字符。伪代码:

tokens = split(string," ")
for each token in tokens,
  if token = "-", skip it
  otherwise print "-" and the token
正则表达式:

var sampleString = "this - is a string   - with hyphens  -     in it";
var trim = Regex.Replace(sampleString, @"\s*-\s*", "-" );

因为每个人都会提出一个正则表达式解决方案,所以我向您介绍一个非正则表达式解决方案:

string s = "this - is a string   - with hyphens  -     in it";
string[] groups = s.Split(
                       new[] { '-', ' ' },
                       StringSplitOptions.RemoveEmptyEntries
                  );
string t = String.Join("-", groups);        

正则表达式是你在这里的朋友。 您可以创建一个模式,其中所有连续的空格/连字符都是一个匹配项

  var hyphenizerRegex = new Regex(@"(?:\-|\s)+");
  var result = hyphenizerRegex.Replace("a - b c -d-e", "-");

如果这是一个使用正则表达式和不使用正则表达式一样容易解决的问题,那么不使用正则表达式将有助于找到更简单、更容易理解的解决方案+1.@AndyPerfect:是。正则表达式被过度使用(为了强调而重复字母也是如此)。希望使其尽可能明确。斯科特似乎不知道正则表达式,所以我想说清楚,它将是一个空格或连字符。(在他看了一些正则表达式备忘单后)