2016-08-31 23 views
-1

我想要做的是如果用戶輸入四個字符(如0500),我想在第二個字符後添加「:」,以便它變爲05:00。從試驗和錯誤它似乎不能正確插入。使用C#中輸入特定長度的字符串時的插入方式

所以我的代碼部分是

 string timeInput = Console.ReadLine(); 
     string[] timeSplit = timeInput.Split(':'); 

     if(timeInput.Length == 4) { // if string = four 
      timeInput = timeInput.Insert(1, ":"); 
      } 
+0

你錯過了正確的索引好友。應該是2而不是1. – user3185569

+0

不要混用術語「字符串」和「字符」。我編輯了你的問題。 – JimHawkins

回答

1

更換

timeInput = timeInput.Insert(1, ":"); 

timeInput = timeInput.Insert(2, ":"); 

第二個索引

string 0 5 0 0 
index 0|1|2|3|4 
0在插入
3

如果您的輸入不包含任何':',則不能通過':'拆分字符串。所以你不需要變量timeSplit。你可以這樣做:

string timeInput = Console.ReadLine(); 
if (timeInput.Length == 4) // if input = "0500" -> true 
    timeInput = timeInput.Insert(2, ":"); 
Console.WriteLine(timeInput); // Output: 05:00 

隨着timeInput.Insert(1, ":")你會得到「0:500」作爲輸出。

+0

是的,因爲我在這裏想要做的是如果輸入像05:00是通過拆分,但如果輸入0500我想將其更改爲05:00。 – lufee

+0

哦,我明白了,去之後如果聲明 – lufee

+0

必須聲明拆分我的愚蠢錯誤是爲了放1,現在才意識到 – lufee

0

Insert方法的第一個參數是要插入任何字符的索引號,後兩位數字索引號是2所以應該2代替1

timeInput = timeInput.Insert(2, ":"); 

,爲什麼你你劈裂輸入使用:你沒有在其中插入:嗎? innsert :後splite是正確的我猜

string timeInput = Console.ReadLine(); 
if(timeInput.Length == 4) 
{ // if string = four 
    timeInput = timeInput.Insert(2, ":"); 
} 
string[] timeSplit = timeInput.Split(':'); 
0

string單個字符被稱爲char

雖然string的長度爲4分度從0開始!

string timeInput = "0500" 

當索引它它看起來像這樣:

timeInput [0] - > 0

timeInput [1] - > 5

timeInput [2] - > 0

timeInput [3] - > 0

這就是爲什麼你需要把:在位置2

if(timeInput.Length == 4) // if string = four 
{ 
    timeInput = timeInput.Insert(2, ":"); 
} 
相關問題