如何在字符串中特定字符之间删除空格?

3

我有一个字符串,类似于这样:

string sampleString = "this - is a string   - with hyphens  -     in it";

需要注意的是,这里左右两侧的连字符周围有随机数量的空格。目标是用连字符替换字符串中的空格(因此字符串中的连字符会出现问题)。因此,我想要的结果应该像这样:

"this-is-a-string-with-hyphens-in-it"。

目前我正在使用:

sampleString.Trim().ToLower().Replace(" ", "-")

但是这会导致以下输出:

"this---is-a-string------with-hyphens--------in-it"

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

谢谢!

8个回答

9

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

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

2
如果一个问题使用正则表达式和不使用一样容易解决,那么不使用正则表达式会更简单、更易于理解。+1。 - AndyPerfect
1
@AndyPerfect:是的。正则表达式被过度使用了(重复字母也是为了强调而过度使用)。 - jason

6

尝试使用 System.Text.RegularExpressions.Regex

只需调用:

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

1

这看起来像是正则表达式的工作(或者如果你更喜欢的话,可以使用分词)。

使用正则表达式,您可以吞掉所有空格和连字符,并将其替换为一个连字符。此表达式匹配任意数量的空格和连字符:

[- ]+

或者你可以通过空格将字符串分割成标记,然后在标记之间使用连字符重新组合字符串,除非该标记本身就是一个连字符。 伪代码:

tokens = split(string," ")
for each token in tokens,
  if token = "-", skip it
  otherwise print "-" and the token

0

试试这个:

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 ;
}

0

正则表达式:

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

0

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

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

想尽可能明确。Scott似乎不了解正则表达式,所以我想要明确一下,它将是一个空格或连字符。(在他看了一些正则表达式备忘单后) - Robert Giesecke

0

你可以在一行代码中完成这个任务

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

0

如果您想要保留所有单词和现有的连字符,那么另一种方法是将字符串拆分为一个数组,在空格处断开。然后重新构建字符串,忽略任何空格,同时在适当的位置插入连字符。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接