2012年2月9日 星期四

[C#基礎]-字串比對,模擬網路遮罩判斷

[C#基礎]-字串比對,模擬網路遮罩判斷


本篇要分享字串比對,模擬網路遮罩判斷,有興趣的同好,歡迎來一下 ^ ^












程式碼



using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

 

namespace CS_char_Compare

{

    class Program

    {

        //字串比對,模擬網路遮罩判斷

        publicbool charCompare(string s, string d)

        {

            byte[] byte_s = System.Text.Encoding.Default.GetBytes(s);//string -> byte

            byte[] byte_d = System.Text.Encoding.Default.GetBytes(d);//string -> byte

            int i = 0;

            int x=0;

            int y=0;

            for (i = 0; i < d.Length; i++)

            {

                x = byte_s[i];//byte -> int

                y = byte_d[i];//byte -> int

                if (byte_d[i]!='x')//未定義不用判斷

                {

                    if (x != y)

                    {

                        returnfalse;//只要一個不同,就回傳FALSE

                    }

                }

            }

            returntrue;//全部相同

        }

        staticvoid Main(string[] args)

        {

            Program p=new Program();

 

            string s="0011001100110011";//資料

            string d="xxxxxxxx00110011";//判斷,x代表未定義

            bool blncheck;

            blncheck = p.charCompare(s, d);

            Console.WriteLine(s);

            Console.WriteLine(d);

            if (blncheck)

            {

                Console.WriteLine("true");

            }

            else

            {

                Console.WriteLine("false");

            }

            string s1= "0011001100110011";//資料

            string d1= "xxxxxx1100111011";//判斷,x代表未定義

            blncheck = p.charCompare(s1, d1);

            Console.WriteLine(s1);

            Console.WriteLine(d1);

            if (blncheck)

            {

                Console.WriteLine("true");

            }

            else

            {

                Console.WriteLine("false");

            }

            string s2 = "0011001100110011";//資料

            string d2 = "xxxxxx1100110011";//判斷,x代表未定義

            blncheck = p.charCompare(s2, d2);

            Console.WriteLine(s2);

            Console.WriteLine(d2);

            if (blncheck)

            {

                Console.WriteLine("true");

            }

            else

            {

                Console.WriteLine("false");

            }

            Console.Read();

        }

    }

}

 



 


沒有留言:

張貼留言