[C#][VB.NET]處理IP字串問題

  • 11253
  • 0
  • 2010-08-02

處理IP字串問題,把IP字串10.0.001.2處理成10.0.1.2

 

1. 問題描述

如何把 IP字串 10.0.001.2 處理成 10.0.1.2

 

2. 方法

在此提供一種作法,流程為 透過 Splt 切割字串,並且將字串轉數字

此外,建議在字串轉數字的過程中,判斷是否有數字以外的字元,或者透過 Regex 判斷此字串是否符合IP規則。

2.1 程式碼

C#

            string strIP = "10.0.001.2";
            string[] strSplitIP = strIP.Split('.');
            StringBuilder sbIP = new StringBuilder("");
            for (int i = 0; i < strSplitIP.Length; i++)
            {
                int temp = Int32.Parse(strSplitIP[i]);
                sbIP.Append("." + temp.ToString());
            }
            sbIP = sbIP.Remove(0, 1);

 

VB.NET

        Dim strIP As String = "10.0.001.2"
        Dim strSplitIP As String() = strIP.Split(".")
        Dim sbIP As String = String.Empty
        Dim i As Integer
        For i = 0 To strSplitIP.Length - 1
            sbIP += "." & Int32.Parse(strSplitIP(i))
        Next
        sbIP = sbIP.Remove(0, 1)

 

2.2 執行結果

sbIP = 10.0.1.2