2017-03-07 58 views
0

我需要從用戶請求一個字,然後將其寫在不同的行如:添加新角色的每一行C#

w 
wo 
wor 
word 

第一次尋求幫助這裏。我一直在嘗試一個小時。

編輯:

Console.WriteLine("Enter a word:"); 

string word; 
word = Console.ReadLine(); 

for (int i = 0; i < word.Length; i++) 
{ 
    Console.WriteLine(word[i]); 
} 
+3

你可以顯示你試過什麼,它不工作 – Jonesopolis

+0

[Environment.NewLine](https://msdn.microsoft.com/en-us/library/system.environment.newline(v = vs .110).aspx) –

+0

@ user7673816:你的代碼的輸出與期望的輸出有什麼不同?還需要做些什麼來糾正它? – David

回答

4

所以你靠近,但你可以看到,你的每次循環,你只寫在指數i在這個詞的一個字母。

你需要做的(如一個簡單的解決方案)什麼是創造另一個字符串,你「建立」以及與每個循環迭代打印出來:

string builder = ""; 
for (int i = 0; i < word.Length; i++) 
{ 
    builder += word[i]; 
    Console.WriteLine(builder); 
} 
+0

謝謝,這正是我正在尋找的! – Bontano

+2

+1對於一個不錯的,簡單的答案是直接和重點,並儘可能多地使用OP的原始代碼 – David

0

您也可以使用LINQ實現它:

Console.WriteLine("Enter a word:"); 
string word = Console.ReadLine().Trim(); 
word.Select((c, i) => word.Substring(0, i + 1)) 
    .ToList() 
    .ForEach(Console.WriteLine); 
+2

是的,這個工作,但OP一直在努力創建基本算法,所以我認爲投擲一堆LINQ在他/她沒有解釋每件事情會做什麼只會導致更多的混淆。 – David

1

您可以使用Substring來解決問題:

Console.WriteLine("Enter a word:"); 

string word = Console.ReadLine(); 
for (int i = 0; i < word.Length; i++) 
{ 
    Console.WriteLine(word.Substring(0, i+1)); 
} 

見這fiddle