在C#中破坏驼峰案例功能

时间:2018-08-12 18:24:53

标签: c# camelcasing

我正在尝试在代码战中解决此问题,但我不知道这有什么问题。错误提示:

  

System.ArgumentOutOfRangeException:长度不能小于零。

     

参数名称:长度

我将不胜感激

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

1 个答案:

答案 0 :(得分:2)

这是一个水晶球(逆向工程)的时间。似乎,您想添加空间' ') >每个大写字符之前:

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

如果这是您的初始任务,则可以像这样实现它

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 
}

如果您喜欢旧的 loop 好的解决方案:

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

最后,您可以尝试正则表达式

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

  return Regex.Replace(str, @"(\p{Lu})", " $1");
}