1

I need to take a sentence in that is all on one line with no spaces and each new word has a captial letter EX. "StopAndSmellTheRoses" and then convert it to "Stop and smell the roses" This is my function that I have but I keep getting an argument out of range error on the insert method. Thanks for any help in advance.

private void FixSentence()
{
    // String to hold our sentence in trim at same time
    string sentence = txtSentence.Text.Trim();

    // loop through the string
    for (int i = 0; i < sentence.Length; i++)
    {
        if (char.IsUpper(sentence, i) & sentence[i] != 0)
        {
            // Change to lowercase
            char.ToLower(sentence[i]);

            // Insert space behind the character
            // This is where I get my error
            sentence = sentence.Insert(i-1, " ");
        }
    }

    // Show our Fixed Sentence
    lblFixed.Text = "";
    lblFixed.Text = "Fixed: " + sentence;
}
Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
amedeiros
  • 939
  • 2
  • 15
  • 24

4 Answers4

3

The best way to build up a String in this manner is to use a StringBuilder instance.

var sentence = txtSentence.Text.Trim();
var builder = new StringBuilder();
foreach (var cur in sentence) {
  if (Char.IsUpper(cur) && builder.Length != 0) {
    builder.Append(' ');
  }
  builder.Append(cur);
}

// Show our Fixed Sentence
lblFixed.Text = "";
lblFixed.Text = "Fixed: " + builder.ToString();

Using the Insert method creates a new string instance every time resulting in a lot of needlessly allocated values. The StringBuilder though won't actually allocate a String until you call the ToString method.

JaredPar
  • 733,204
  • 149
  • 1,241
  • 1,454
1

You can't modify the sentence variable in the loop that is going through it.

Instead, you need to have a second string variable that you append all of the found words.

NotMe
  • 87,343
  • 27
  • 171
  • 245
1

Here is the answer

var finalstr = Regex.Replace(
        "StopAndSmellTheRoses",
        "(?<=[a-z])(?<x>[A-Z])|(?<=.)(?<x>[A-Z])(?=[a-z])|(?<=[^0-9])(?<x>[0-9])(?=.)",
        me => " " + me.Value.ToLower() 
    );

will output

Stop and smell the roses
Community
  • 1
  • 1
L.B
  • 114,136
  • 19
  • 178
  • 224
0

Another version:

public static class StringExtensions
{
  public static string FixSentence(this string instance)
  {
    char[] capitals = Enumerable.Range(65, 26).Select(x => (char)x).ToArray();
    string[] words = instance.Split(capitals);
    string result = string.Join(' ', words);
    return char.ToUpper(result[0]) + result.Substring(1).ToLower();
  }
}
Erik Philips
  • 53,428
  • 11
  • 128
  • 150