两道简单的机试题目
两道简单的机试题目 1.统计一个英语句子中最大单词的长度 2.统计一个字符串内大写字母,空格以及数字的个数
class Program
{
static void Main(string[] args)
{
CountLength();
CountNum();
Console.Read();
}
//统计一个英语句子中最大单词的长度
private static void CountLength()
{
string test = "I am a good man";
string[] arr = test.Split(' ');
int max = 0;
foreach (string str in arr)
{
int len = str.Length;
if (len > max)
{
max = len;
}
}
Console.WriteLine(max);//结果正确:4
}
//统计一个字符串内大写字母,空格以及数字的个数
解法一:
private static void CountNum()
{
string test = "Avs fdfdKLJL 3232 dsdss323232LOJO";
int numUpper = 0, numSpace = 0, numNumber = 0;
foreach (char ch in test)
{
if (ch >= 'A' && ch <= 'Z')
{
numUpper++;
}
if (ch >= '0' && ch <= '9')
{
numNumber++;
}
if (ch == ' ')
{
numSpace++;
}
}
Console.WriteLine("大写字母数量:" + numUpper + "数字数量:" + numNumber + "空格数量:" + numSpace);
}
}
解法二:使用正则表达式
Regex rx = new Regex(@"[A-Z]");
string str = "Avs fdfdKLJL 3232 dsdss323232LOJO";
int count = rx.Matches(str).Count;
MatchCollection mc = rx.Matches(str);
Console.WriteLine(mc.Count);
Console.WriteLine(count);
rx = new Regex(@"[\d]");
count = rx.Matches(str).Count;
Console.WriteLine(count);
rx = new Regex(@"[\s]");
count = rx.Matches(str).Count;
Console.WriteLine(count);
Console.ReadKey();