Home >Backend Development >C++ >How to Efficiently Insert Spaces Before Uppercase Letters in a String?

How to Efficiently Insert Spaces Before Uppercase Letters in a String?

Linda Hamilton
Linda HamiltonOriginal
2024-12-29 21:21:15784browse

How to Efficiently Insert Spaces Before Uppercase Letters in a String?

Inserting Spaces into Casing Transitions

The objective is to transform a string like "ThisStringHasNoSpacesButItDoesHaveCapitals" into "This String Has No Spaces But It Does Have Capitals" by introducing spaces preceding uppercase characters.

Regex Approach

Regular expressions can indeed be used for this purpose. The regex "[A-Z]" identifies uppercase letters, and " $0" adds a space before each match:

System.Text.RegularExpressions.Regex.Replace(value, "[A-Z]", " <pre class="brush:php;toolbar:false">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 < text.Length; i++)
  {
    if (char.IsUpper(text[i]))
      if ((text[i - 1] != ' ' && !char.IsUpper(text[i - 1])) ||
          (preserveAcronyms && char.IsUpper(text[i - 1]) &&
           i < text.Length - 1 && !char.IsUpper(text[i + 1])))
        newText.Append(' ');
    newText.Append(text[i]);
  }
  return newText.ToString();
}
")

However, regexes can be computationally expensive and less readable for complex patterns.

Iterative Approach

An alternative approach is to iterate through the string character by character:

This function checks for the transition between lowercase to uppercase characters, handling acronyms optionally.

Performance Comparison

Performance-wise, the iterative approach significantly outperforms the regex approach, demonstrating a 92.4% reduction in execution time for a string with 1,000 consecutive capital letters. It trades off code simplicity for speed.

Ultimately, the choice between these approaches depends on the specific performance and readability requirements of each project.

The above is the detailed content of How to Efficiently Insert Spaces Before Uppercase Letters in a String?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn