兩道簡單的機試題目

兩道簡單的機試題目  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);
        }
    }string

    解法二:使用正則表達式it

            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);io

            rx = new Regex(@"[\d]");
            count = rx.Matches(str).Count;
            Console.WriteLine(count);class

            rx = new Regex(@"[\s]");
            count = rx.Matches(str).Count;
            Console.WriteLine(count);test

            Console.ReadKey();foreach

相關文章
相關標籤/搜索