[ASP.NET][C#]字串倒退

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




開一個新的網頁命名為

WebForm3

 

 


程式碼示範


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace WebTestC
{
    public partial class WebForm3 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                Label1.Text = "9876543210";
                TextBox1.Text = "9876543210";
                HyperLink1.Text = "9876543210";
            }
            Button1.Text = "Label1長度減一個字元";
            Button2.Text = "TextBox1長度減一個字元";
            Button3.Text = "HyperLink1長度減一個字元";
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            //判斷Label1.Text的字串不是空白
            if (!string.IsNullOrWhiteSpace (Label1.Text))
            //如果是空白的話就不執行下面這一行程式
            Label1.Text = Label1.Text.Substring(0, Label1.Text.Length - 1);
        }

        protected void Button2_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrWhiteSpace(TextBox1.Text))
            TextBox1.Text = TextBox1.Text.Substring(0, TextBox1.Text.Length - 1);
        }

        protected void Button3_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrWhiteSpace(HyperLink1.Text))
            HyperLink1.Text = HyperLink1.Text.Substring(0, HyperLink1.Text.Length - 1);
        }
    }
}


 

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



using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class WebForm3 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            Label1.Text = TextBox1.Text = HyperLink1.Text = "9876543210";
        }
        Button1.Text = "Label1長度減一個字元";
        Button2.Text = "TextBox1長度減一個字元";
        Button3.Text = "HyperLink1長度減一個字元";
    }

    private string cmd(string value)
    {
        //判斷字串是空白,就直接回傳回去
        if (string.IsNullOrEmpty(value)) return value;
        //假如不是空白字串就 回傳一個參數 字串分割的結果回去
        return value.Substring(0, value.Length - 1);
    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        Label1.Text = cmd(Label1.Text);
    }
    protected void Button2_Click(object sender, EventArgs e)
    {
        TextBox1.Text = cmd(TextBox1.Text);
    }
    protected void Button3_Click(object sender, EventArgs e)
    {
        HyperLink1.Text = cmd(HyperLink1.Text);
    }
}

 

 


string:宣告的字串

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

Substring:擷取字串內裡的文字

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

 

 


 

示範呈現的頁網頁