String Substring() Method
The .net String class’s Substring() method allows us to retrieve a substring from a String object. This method has two overloaded methods those are Substring(Int32) and Substring(Int32, Int32).
The Substring(Int32) overloaded method retrieves a substring from a String by starting at a specified character position and continuing to the end of the String. This method needs to pass a parameter name startIndex. This parameter data type is Int32. The startIndex parameter value specifies a zero-based starting character position of the String. This method does not modify the current string instance, it returns a new String that begins at the startIndex position of the current String.
The Substring(Int32, Int32) overloaded method allows us to get a substring from a String that starts a specified character position String and has a specified length. This method has two parameters, which are startIndex and length. The startIndex is the zero-based starting character position of a substring in this instance. The length parameter specifies the number of characters in the substring.
The following asp.net c# example code demonstrates to us how we can get a substring from a String in the .net framework.
Substring.aspx
<%@ Page Language="C#" %>
<!DOCTYPE html>
<script runat="server">
protected void page_Load(object sender, System.EventArgs e) {
if(!this.IsPostBack)
{
TextBox1.Text = "Jones is here.";
}
}
protected void Button1_Click(object sender, System.EventArgs e) {
string myString = TextBox1.Text.ToString();
string subString = myString.Substring(0,5);
Label1.Text = "Substring[0,5]: " + subString;
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>How to get substring from a string in asp.net</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h2 style="color:Navy">asp.net string example: Substring()</h2>
<asp:Label
ID="Label1"
runat="server"
Font-Size="Large"
ForeColor="Firebrick"
Font-Bold="true"
Font-Italic="true"
>
</asp:Label>
<br /><br />
<asp:Label
ID="Label2"
runat="server"
Text="Test String"
ForeColor="Purple"
>
</asp:Label>
<asp:TextBox
ID="TextBox1"
runat="server"
BackColor="Purple"
ForeColor="Snow"
>
</asp:TextBox>
<br /><br />
<asp:Button
ID="Button1"
runat="server"
OnClick="Button1_Click"
Font-Bold="true"
Text="Get Substring [0,5]"
ForeColor="Purple"
/>
</div>
</form>
</body>
</html>