Search code examples
c#camelcasing

Break Camel Case function in c#


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;
}

Solution

  • 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");
    }