c# - 如何删除字符串中特定字符之间的空格?

标签 c# string

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

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

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

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

目前我正在使用:

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

但这会导致以下输出:

“this---is-a-string------with-hyphens--------in-it”

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

谢谢!

最佳答案

因为大家都会提出正则解决方案,我给大家介绍一个非正则解决方案:

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

关于c# - 如何删除字符串中特定字符之间的空格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4786873/

相关文章:

c++ - Visual C++ : Migrating traditional C and C++ string code to a Unicode world

python - 使用 split 从文件中的一行读取特定字符串

c - 当你用c中的gets()函数获取它时,如何在char数组的后面添加一个字符?

c# - 如何使用电子邮件模板c#发送电子邮件

c# - VS2017中的MVC 3错误: The name 'ViewData' does not exist in the current context

c# - 流利的 NHibernate : Map property without foreign key?

c# - 公共(public)语言运行时使用 ClickOnce 检测到无效程序

C# PCL HMACSHAX 与 BouncyCaSTLe-PCL

string - 将相同的字符串附加到 Groovy 中的字符串列表

c# - 用于检查字符串是否包含所有特定符号的正则表达式