題目要求:用戶隨機輸入字母及數字組成的字符串,當用戶連續輸入字符串‘hello’時,程序結束用戶輸入,並分別顯示用戶輸入的字母及數字的數目。
代碼:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace 字符操作
{
public class Program
{
public static void Main()
{
char s = '#';
int LetterIndex = 0, DigitIndex = 0;
Console.Write("請輸入一個字符串(當輸入hello時結束):");
turn:if(s!='h')
{
if (char.IsLetter(s))
LetterIndex++;
if (char.IsDigit(s))
DigitIndex++;
s = Console.ReadKey().KeyChar;
}
if (s == 'h')
{
LetterIndex++;
s = Console.ReadKey().KeyChar;
if (s == 'e')
{
LetterIndex++;
s = Console.ReadKey().KeyChar;
if (s == 'l')
{
LetterIndex++;
s = Console.ReadKey().KeyChar;
if (s == 'l')
{
LetterIndex++;
s = Console.ReadKey().KeyChar;
if (s == 'o')
{
LetterIndex++;
Console.WriteLine("\n共有字母{0}個,數字{1}個.", LetterIndex, DigitIndex);
Console.WriteLine("按任意鍵結束.");
Console.ReadKey();
}
else
goto turn;
}
else
goto turn;
}
else
goto turn;
}
else
goto turn;
}
else
goto turn;
}
}
}
題目解析:首先這道題目要求用戶輸入字符串”hello“時結束輸入,不如分別判斷這五個字母,其次需要程序自動結束輸入,我們就需要用Console.ReadKey().KeyChar每次自動讀取用戶輸入的一個字符.