c# - 如何在给定字符串中用 " "替换第二个空格,但不是第一个/最后一个?

标签 c# asp.net

假设我有以下字符串:

string s = "A B  C   D    TESTTEST  BLA BLA      TEST       TEST2"

然后我需要以下内容:

"A B  C   D    TESTTEST  BLA BLA      TEST       TEST2"

所以规则是:
a) 用  
替换每隔一个空格(在非空格字符之间) b) 如果最后一个空格被   替换,尝试将它向后移动(如果可能)一步,这样下一个单词就不会被强制空格触及。

背景:

我想用它来将数据从数据库打印到我的网站。但我想优化强制空间以使用更少的空间。我还希望最后一个强制空格不要触及下一个词(如果可能的话),以便某些搜索引擎更容易捕捉到该词。

我是否需要遍历该字符串中的每个字符并计算出现次数,还是有更简单、更快速、更奇特的方法?

谢谢,两种解决方案都运行良好。
所以我做了一个基准来找出接受哪种解决方案:

@Guffa,您的解决方案需要 22 秒才能运行 100 万次
@Timwi,您的解决方案运行 100 万次需要 7 秒

我会给你们两个都投赞成票,但我会接受 Timwi 的解决方案。

最佳答案

Let’s use a regular expression!

var input = "A B  C   D    TESTTEST  BLA BLA      TEST       TEST2";
var output = Regex.Replace(input, @"  +", m =>
    m.Length == 2 ? "  " :
    m.Length % 2 == 1 ? "  ".Repeat(m.Length / 2) + " " :
    "  ".Repeat(m.Length / 2 - 1) + "  ");

这使用了我写的 string.Repeat 扩展方法:

/// <summary>
/// Concatenates the specified number of repetitions of the current string.
/// </summary>
/// <param name="input">The string to be repeated.</param>
/// <param name="numTimes">The number of times to repeat the string.</param>
/// <returns>A concatenated string containing the original string the specified number of times.</returns>
public static string Repeat(this string input, int numTimes)
{
    if (numTimes == 0) return "";
    if (numTimes == 1) return input;
    if (numTimes == 2) return input + input;
    var sb = new StringBuilder();
    for (int i = 0; i < numTimes; i++)
        sb.Append(input);
    return sb.ToString();
}

顺便说一下,如果“节省空间”指的是带宽/存储空间,您可以使用 "\xa0" 使其更加紧凑" ",在 HTML 中是等效的。

关于c# - 如何在给定字符串中用 "&nbsp;"替换第二个空格,但不是第一个/最后一个?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3795693/

相关文章:

c# - HTML 扩展方法在表单中不起作用

c# - 如何在众多网站中共享通用功能?

c# - 如何使用 Microsoft.Build.Evaluation.Project.RemoveItem

c# - 将 ASP.NET Core 应用程序部署到 Azure 会导致空白页面

c# - 有什么办法可以防止dll在reflector之类的软件中打开?

C# 自定义 Observable 集合——我应该使用组合还是继承?

c# - 如何将 List<KeyValuePair<int,int>> 转换为 int[][]?

c# - 为什么我不能检查连接字符串上的空引用?

c# - 通过YouTube API访问“喜欢”或“不喜欢”功能

asp.net - 在发布时强制将外部文件复制到 bin 文件夹