Roman Melnyk Roman Melnyk - 1 month ago 5
C# Question

System.ArgumentOutOfRangeException Error

using System;
using System.Text.RegularExpressions;
using System.Globalization;

public class Kata
{
public static string ToCamelCase(string str)
{
TextInfo myTI = new CultureInfo("en-US", false).TextInfo;
string clearStr = Regex.Replace(myTI.ToTitleCase(str), @"_|-", "");
return clearStr = str.Substring(0, 3) + clearStr.Remove(0, 3);
}
}


input - > ToCamelCase("the_stealth_warrior")

input - > ToCamelCase("The-Stealth-Warrior")


Error: System.ArgumentOutOfRangeException : Index and length must
refer to a location within the string. Parameter name: length


What am I doing wrong?

Answer

You have the exception thrown at Substring(0, 3) or Remove(0, 3) in case either str or clearStr is shorter than 3. I suggest adding validation:

public static string ToCamelCase(string str) {
  // if str is null or too short 
  if (string.IsNullOrEmpty(str))
    return str;
  else if (str.Length < 3)
    return str;

  TextInfo myTI = new CultureInfo("en-US", false).TextInfo;
  string clearStr = Regex.Replace(myTI.ToTitleCase(str), @"_|-", "");

  // if clearStr is too short
  if (clearStr.Length < 3)
    return str;

  return clearStr = str.Substring(0, 3) + clearStr.Remove(0, 3);
}
Comments