using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text.RegularExpressions;
public partial class _default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string dataStr = "010333FF0001BB7E";
//prevent odd length such as 012 >> 0012 >> 00 ,12
if (dataStr.Length % 2 == 1) dataStr = "0" + dataStr;
// method A
string[] ResultArr = (from Match m in Regex.Matches(dataStr, "[0-9a-fA-F]{2}")
select m.Value).ToArray();
// method B
List<string> ResultList = new List<string>();
int packSize = 2;
for (int i = 0; i < dataStr.Length ; i += packSize)
ResultList.Add(dataStr.Substring(i, packSize));
}
}
}
ทำได้มากกว่าหนึ่งวิธีค่ะ ชอบแบบไหนก้อลองดูค่ะ
ในที่นี้
แบบ A ทำงานช้ากว่าแต่ก็รัดกุมกว่า
แบบ B แบบเรียบง่ายค่ะ
Imports System.Collections.Generic
Imports System.Linq
Imports System.Web
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Text.RegularExpressions
Public Partial Class _default
Inherits System.Web.UI.Page
Protected Sub Page_Load(sender As Object, e As EventArgs)
If Not IsPostBack Then
Dim dataStr As String = "010333FF0001BB7E"
'prevent odd length such as 012 >> 0012 >> 00 ,12
If dataStr.Length Mod 2 = 1 Then
dataStr = "0" & dataStr
End If
' method A
Dim ResultArr As String() = (From m In Regex.Matches(dataStr, "[0-9a-fA-F]{2}")m.Value).ToArray()
' method B
Dim ResultList As New List(Of String)()
Dim packSize As Integer = 2
Dim i As Integer = 0
While i < dataStr.Length
ResultList.Add(dataStr.Substring(i, packSize))
i += packSize
End While
End If
End Sub
End Class