2016-11-01 34 views
0
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);  
    } 
} 

輸入 - > ToCamelCase( 「the_stealth_warrior」)System.ArgumentOutOfRangeException錯誤

輸入 - > ToCamelCase(以下簡稱 「隱身戰士」)

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

我在做什麼錯?

+0

Whay是''a「','」ab「'所需的輸出嗎? –

+0

我剛剛試過你的代碼。它運行時不會在我的機器上拋出異常。你確定你沒有通過相同的其他值,如String.Empty? –

回答

0

你必須要在Substring(0, 3)Remove(0, 3)拋出的異常的情況下,無論是strclearStr3短。我建議增加驗證:如果你傳遞一個字符串作爲str參數是少於3個字符

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

檢查strclearStr長度。 Substring將拋出此錯誤,如果字符串長度小於您選擇/刪除。

0

您的代碼將拋出此異常。我建議在開始時爲此添加一個檢查,並定義這些類型值的期望結果。

相關問題