數字查詢統計重複

萬里無雲便是我發表於2017-03-24


問題描述:


輸入一串數字和要查詢的數字,統計該傳中重複出現了幾次要查詢的數字


程式碼:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace ConsoleApplication1
{
    class Program
    {
        
        static void Main(string[] args)
        {
            #region 設定為可迴圈查詢
            MyClass class1 = new MyClass();
            while (true)
            {
                Console.WriteLine("請輸入一串數字");
                string str = Console.ReadLine();
                if (class1.isNum(str))
                {
                    Console.WriteLine("請輸入您要查詢的一個數字");
                    String f = Console.ReadLine();
                    char find;
                    char.TryParse(f, out find);
                    //確保輸入的是一個數字
                    if (class1.isNum(find.ToString()))
                    {
                        class1.CountNum(str, find);
                    }
                    else
                        Console.WriteLine("您輸入的格式錯誤!請重新輸入。。。");
                }
                else
                    Console.WriteLine("您輸入的格式錯誤!請重新輸入。。。");
            }

            Console.ReadKey();
            #endregion
        }
       
    }
    class MyClass
    {
        #region 判斷字串是否都是數字
        public Boolean isNum(string val)
        {  
          
            Regex rex = new Regex(@"^[+-]?\d*$");//如123.4567
            if (rex.IsMatch(val))//如果符合這個正規表示式
            {
                return true;
            }
            return false;
           
        }
        #endregion

        #region 查詢數字並記錄數字出現次數的方法
        public void CountNum(string str, char find)
        {
            int n = 0;
            char[] word = str.ToCharArray();//將字串裡面的每個字元轉換為字元陣列裡面的元素
            char b = Convert.ToChar(find);
            for (int i = 0; i < word.Length; i++)
            {
                if (word[i] == b)
                    n++;
            }
            Console.WriteLine("字串中出現{0}次", n);
        }
        #endregion
    }

}



執行結果:


相關文章