[ASP.NET][VB.NET]字串倒退

摘要:[ASP.NET][VB.NET]字串倒退




開一個新的網頁命名為

WebForm3

 

 


程式碼示範


Public Class WebForm3
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If Not IsPostBack Then
            Label1.Text = "9876543210"
            TextBox1.Text = "9876543210"
            HyperLink1.Text = "9876543210"
        End If
        Button1.Text = "Label1長度減一個字元"
        Button2.Text = "TextBox1長度減一個字元"
        Button3.Text = "HyperLink1長度減一個字元"
    End Sub

    Protected Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button1.Click
        '判斷Label1.Text的字串不是空白
        If Not String.IsNullOrWhiteSpace(Label1.Text) Then
            '如果是空白的話就不執行下面這一行程式
            Label1.Text = Label1.Text.Substring(0, Label1.Text.Length - 1)
        End If
    End Sub

    Protected Sub Button2_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button2.Click
        If Not String.IsNullOrWhiteSpace(TextBox1.Text) Then
            TextBox1.Text = TextBox1.Text.Substring(0, TextBox1.Text.Length - 1)
        End If
    End Sub

    Protected Sub Button3_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button3.Click
        If Not String.IsNullOrWhiteSpace(HyperLink1.Text) Then
            HyperLink1.Text = HyperLink1.Text.Substring(0, HyperLink1.Text.Length - 1)
        End If
    End Sub
End Class

 



經Allen Kuo老師指導後修改的程式碼:


Public Class WebForm1
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If Not IsPostBack Then
            Label1.Text = "9876543210"
            TextBox1.Text = "9876543210"
            HyperLink1.Text = "9876543210"
        End If
        Button1.Text = "Label1長度減一個字元"
        Button2.Text = "TextBox1長度減一個字元"
        Button3.Text = "HyperLink1長度減一個字元"
    End Sub
    Private Function cmd(value As String) As String
        '判斷字串是空白,就直接回傳回去
        If String.IsNullOrEmpty(value) Then
            Return value
        End If
        '假如不是空白字串就 回傳一個參數 字串分割的結果回去
        Return value.Substring(0, value.Length - 1)
    End Function
    Protected Sub Button1_Click(sender As Object, e As EventArgs)
        Label1.Text = cmd(Label1.Text)
    End Sub
    Protected Sub Button2_Click(sender As Object, e As EventArgs)
        TextBox1.Text = cmd(TextBox1.Text)
    End Sub
    Protected Sub Button3_Click(sender As Object, e As EventArgs)
        HyperLink1.Text = cmd(HyperLink1.Text)
    End Sub
End Class

 

 


程式碼解說:
 

string:宣告的字串

IsNullOrWhiteSpace字串是否為 null、空白,或只由空白字元組成的字串(.NET Framework 4版本)

Substring擷取字串內裡的文字

Length字串長度,簡單說內容有幾個字就是全部包含在內


 


 

示範呈現的網頁