-8

I'm trying to solve this problem in codewars but i didn't know what is wrong about it. Error said :

System.ArgumentOutOfRangeException : Length cannot be less than zero.

Parameter name: Length

I'll appreciate any help

public static string BreakCamelCase(string str)
{   
    if (str.Length < 1) 
        return "";
   
    var res = "";

    foreach (var c in str)
    {
        if (char.IsUpper(c))
            res = str.Substring(0,str.IndexOf(c)) + " " + str.Substring(str.IndexOf(c));

        str = res;
    } 
            
    return res;
}
Community
  • 1
  • 1
  • 2
    It is a missing braces around the block under the if condition. WIthout the braces the second statement is always executed – Steve Aug 12 '18 at 18:28
  • 3
    You shouldn't modify `str` inside the foreach. – Sach Aug 12 '18 at 18:28
  • 1
    If you single-step through the code in your debugger you'll see that `str = res` always executes, because you forgot to use `{ }` after your if. Learning to use your debugger will help you a lot to figure out logic errors, the compiler only finds syntax errors. Also as mentioned it's dangerous and easy to mess up if you modify a string (and other collections) you are looping through with foreach, building a copy is sometimes safer. – Dave S Aug 12 '18 at 18:30

1 Answers1

5

It's a very time for a crystal ball (reverse engineering)... It seems, that you want to add space (' ') before each uppercase character:

"MyOwnString" -> " My Own String"
"something"   -> "something"
"camelCase"   -> "camel Case"
"наРусском"   -> "на Русском"    // all languages (e.g. Russian), not only English

If it's your initial task, you can implement it like this

public static string BreakCamelCase(string str) {   
  // "str.Length<1" will fail in case str == null. Do not re-invent the wheel
  if (string.IsNullOrEmpty(str))
    return str;

  // A simple Linq query:
  return string.Concat(str       // concat all chunks
   .Select(c => char.IsUpper(c)  // which can be
      ? " " + c.ToString()       //   uppercase
      : c.ToString()));          //   others 
}

If you prefer good old loop solution:

public static string BreakCamelCase(string str) {   
  if (string.IsNullOrEmpty(str))
    return str;

  // We want to build string in a loop. 
  // StringBuilder has been specially desinged for this
  StringBuilder sb = new StringBuilder();

  foreach (var c in str) {
    if (char.IsUpper(c))    
      sb.Append(' ');

    sb.Append(c);
  }

  return sb.ToString();
}

Finally, you can try regular expressions:

public static string BreakCamelCase(string str) {   
  if (string.IsNullOrEmpty(str))
    return str;

  return Regex.Replace(str, @"(\p{Lu})", " $1");
}
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215