将字符串中的数字和字符分离的技术例如(the9 city)分解成(the city)和9

http://dev.poptool.net/wangluo/asp.net/suanfa/13104.html

原始字符串
string completeString = "the9 city";
转换完成的字符串
string stringVal = "the city";
int numericVal = 9;
aspx文件
<%@ Page language="c#" Codebehind="StringParser.aspx.cs" AutoEventWireup="false" Inherits="HowTo._20020221.StringParser" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML>
<HEAD>
  <title>StringParser</title>
  <meta name="GENERATOR" Content="Microsoft Visual Studio 7.0">
  <meta name="CODE_LANGUAGE" Content="C#">
  <meta name="vs_defaultClientScript" content="JavaScript">
  <meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5">
</HEAD>
<body>
<form id="StringParser" method="post" runat="server">
  <P>
    <STRONG>Enter a Alphanumeric String:</STRONG>
    <asp:RequiredFieldValidator id="RequiredFieldValidator1" runat="server"
      ErrorMessage="* Required" ControlToValidate="TextBox1"></asp:RequiredFieldValidator>
    <BR>
    <asp:TextBox id="TextBox1" runat="server"></asp:TextBox>
    <asp:Button id="btnGo" runat="server" Text="Go!"></asp:Button>
  </P>
  <P>
    <asp:Label id="Label1" runat="server"></asp:Label>
  </P>
  <P>
    <asp:Label id="Label2" runat="server"></asp:Label>
  </P>
</form>
</body>
</HTML>
在页面中我们有一个textbox一个button两个label,我们可以在textbox中输入字符串,然后再label中显示拆分结果,为了证实数值生成的确实是int32我们在计算它们的平方
编辑StringParser.aspx.cs文件
一些必要的设置
using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

namespace HowTo._20020221
{
  public class StringParser : System.Web.UI.Page
  {
    protected System.Web.UI.WebControls.TextBox TextBox1;
    protected System.Web.UI.WebControls.Button btnGo;
    protected System.Web.UI.WebControls.RequiredFieldValidator RequiredFieldValidator1;
    protected System.Web.UI.WebControls.Label Label2;
    protected System.Web.UI.WebControls.Label Label1;
在这个事例中我们不需要page_onload事件所以我们将略过不提
我们看一下btnGo.Click事件
  private void btnGo_Click(object sender, System.EventArgs e)
    {
      System.Text.StringBuilder _string = new System.Text.StringBuilder();
      System.Text.StringBuilder _int = new System.Text.StringBuilder();
      char[] _text;

      //使用ToCharArray()生成character array .
      _text = TextBox1.Text.Trim().ToCharArray(0, TextBox1.Text.Trim().Length);

      for (Int32 i = 0 ; i < _text.Length; i++)
      {
        try
        {
          //试着解析character 成Int32
          Int32.Parse(_text[i].ToString());
          _int.Append(_text[i].ToString());
        }
        catch
        {
          //如果character 不是阿拉伯数字,将发生一个错误"Invalid Input String"
          _string.Append(_text[i].ToString());
        }
      }
      Label1.Text = "String: " + _string.ToString();
      Label1.Text += "<br>Int32: " + _int.ToString();

      Int32 _newInt = Int32.Parse(_int.ToString());

      Label2.Text = "The Int32 value squared is: ";
      Label2.Text += (_newInt * _newInt).ToString();
    }
  }

你可能感兴趣的:(字符串)