String get first character
The following asp.net c# example code demonstrate us how can we get the first character of a string programmatically
at run time in an asp.net application. .Net framework's String Class represent text as a series of Unicode characters.
String Class has no direct method or property to get its first character. So, we need to convert the string object value to a
char array.
String.ToCharArray() method copies the characters in this instance to a Unicode character array. .Net framework's Enumerable.ElementAt<TSource>() method return the element at a specified index in a sequence. So, we can get char array first element by calling the ElementAt() method as this way CharArray.ElementAt(0). .Net framework's Array object contain zero (0) based index. Here, char array first element represent the first character of string.
String.ToCharArray() method copies the characters in this instance to a Unicode character array. .Net framework's Enumerable.ElementAt<TSource>() method return the element at a specified index in a sequence. So, we can get char array first element by calling the ElementAt() method as this way CharArray.ElementAt(0). .Net framework's Array object contain zero (0) based index. Here, char array first element represent the first character of string.
string-get-first-character.aspx
<%@ Page Language="C#" AutoEventWireup="true"%>
<!DOCTYPE html>
<script runat="server">
protected void Button1_Click(object sender, System.EventArgs e)
{
//this section create a string variable.
string plants = "Brown Betty. Meadow Cabbage. Catalina Ironwood. Wild Black Cherry.";
Label1.Text = "string of plants..................<br />";
Label1.Text += plants+"<br />";
//this line get first character of string.
char ch = plants.ToCharArray().ElementAt(0);
Label1.Text += "<br />first character of string: " + ch;
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>c# example - string get first character</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h2 style="color:MidnightBlue; font-style:italic;">
c# example - string get first character
</h2>
<hr width="550" align="left" color="Gainsboro" />
<asp:Label
ID="Label1"
runat="server"
Font-Size="Large"
>
</asp:Label>
<br /><br />
<asp:Button
ID="Button1"
runat="server"
Text="string get first character"
OnClick="Button1_Click"
Height="40"
Font-Bold="true"
/>
</div>
</form>
</body>
</html>

- How to determine whether a string is equals to another string
- String equals case insensitive
- How to escape double quotes in a string
- How to check whether a string starts with number
- How to check whether a string starts with letter
- How to find a substring within a string
- How to find index of a substring in a string
- How to find number of occurrences of a substring in a string
- How to find second occurrence of a substring in a string
- How to remove characters from a string