Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>The regexes will work fine (I even voted up Martin Browns answer), but they are expensive (and personally I find any pattern longer than a couple of characters prohibitively obtuse)</p> <p>This function </p> <pre><code>string AddSpacesToSentence(string text, bool preserveAcronyms) { if (string.IsNullOrWhiteSpace(text)) return string.Empty; StringBuilder newText = new StringBuilder(text.Length * 2); newText.Append(text[0]); for (int i = 1; i &lt; text.Length; i++) { if (char.IsUpper(text[i])) if ((text[i - 1] != ' ' &amp;&amp; !char.IsUpper(text[i - 1])) || (preserveAcronyms &amp;&amp; char.IsUpper(text[i - 1]) &amp;&amp; i &lt; text.Length - 1 &amp;&amp; !char.IsUpper(text[i + 1]))) newText.Append(' '); newText.Append(text[i]); } return newText.ToString(); } </code></pre> <p>Will do it 100,000 times in 2,968,750 ticks, the regex will take 25,000,000 ticks (and thats with the regex compiled).</p> <p>It's better, for a given value of better (i.e. faster) however it's more code to maintain. "Better" is often compromise of competing requirements.</p> <p>Hope this helps :)</p> <p><strong>Update</strong><br> It's a good long while since I looked at this, and I just realised the timings haven't been updated since the code changed (it only changed a little).</p> <p>On a string with 'Abbbbbbbbb' repeated 100 times (i.e. 1,000 bytes), a run of 100,000 conversions takes the hand coded function 4,517,177 ticks, and the Regex below takes 59,435,719 making the Hand coded function run in 7.6% of the time it takes the Regex.</p> <p><strong>Update 2</strong> Will it take Acronyms into account? It will now! The logic of the if statment is fairly obscure, as you can see expanding it to this ...</p> <pre><code>if (char.IsUpper(text[i])) if (char.IsUpper(text[i - 1])) if (preserveAcronyms &amp;&amp; i &lt; text.Length - 1 &amp;&amp; !char.IsUpper(text[i + 1])) newText.Append(' '); else ; else if (text[i - 1] != ' ') newText.Append(' '); </code></pre> <p>... doesn't help at all!</p> <p>Here's the original <em>simple</em> method that doesn't worry about Acronyms</p> <pre><code>string AddSpacesToSentence(string text) { if (string.IsNullOrWhiteSpace(text)) return ""; StringBuilder newText = new StringBuilder(text.Length * 2); newText.Append(text[0]); for (int i = 1; i &lt; text.Length; i++) { if (char.IsUpper(text[i]) &amp;&amp; text[i - 1] != ' ') newText.Append(' '); newText.Append(text[i]); } return newText.ToString(); } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload