How to replace every second space, but not the first / last with "& nbsp;" in the given line?

let's say I have the following line:

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

Then I need the following:

"A B  C   D    TESTTEST  BLA BLA      TEST       TEST2"

So, the rules:
a) replace every second space ( between non-spatial characters ) with  
b) If the last place is replaced by  , try moving it back (if possible) one step so that the next word does not touch the force space.

Background:

I want to use this to print data from a database on my website. But I want to optimize push spaces to use less space. I also want the last forced space not to touch the next word (if possible), so it’s easier for some search engines to catch that word.

Do I need to iterate over each char in this line and count this event, or is there an easier, faster and more bizarre way?

Thanks, both solutions work perfectly.
So I made a benchmark to figure out which decision to make:

@Guffa, your solution takes 22 seconds for 1 million runs
@Timwi, your solution takes 7 seconds for 1 million runs

I will give both of you, but I will decide Timwi.

+3
3

!

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" "&nbsp;", HTML.

+4

:

s = String.Concat(
  Regex.Split(s, "( +)")
  .Select((p, i) => i % 2 == 0 ? p :
    String.Concat(
      Enumerable.Repeat(" &nbsp;", p.Length<3 ? p.Length-1 : p.Length/2-1)
      .ToArray()) +
    (p.Length % 2 == 1 ? " " : "") +
    (p.Length > 2 ? "&nbsp; " : ""))
  .ToArray()
);
+3
s.Replace("  ", " &nbsp;");
0
source

Source: https://habr.com/ru/post/1766583/


All Articles