c# - How to find first index of a character within a string

Find index of character in string
The following asp.net c# example code demonstrate us how can we find index of a specified character in 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 String.IndexOf(Char) overloaded method reports the zero-based index of the first occurrence of the specified Unicode character in this string. String.IndexOf(Char) method has a required parameter named 'value' which data type is System.Char. This parameter value represent a Unicode character to seek.

String.IndexOf(Char) method return a System.Int32 data type integer value. This return value represent the zero-based index position of specified character, if that character is found; otherwise it return -1.

So, we can find index of a character from a string using String.IndexOf(Char) method. We just need to call the method and specify the string instance and a character to search.

<%@ 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 = "Damask Violet. Violet Bloom. Western Redbud. Walnut.";

        Label1.Text = "string of plants..................<br />";
        Label1.Text += plants+"<br />";

        //character to find/search index in string.
        char indexOfCharcterToFind = 'V';

        //this line find/search first index of a character in string
        if (plants.IndexOf(indexOfCharcterToFind) != -1)
            Label1.Text += "<br />character[V] found in string. first index of: ";
            Label1.Text += plants.IndexOf(indexOfCharcterToFind);
            Label1.Text += "<br />character [V] not found in string";
<html xmlns="http://www.w3.org/1999/xhtml">  
<head id="Head1" runat="server">  
    <title>c# example - find index of character in string</title>  
    <form id="form1" runat="server">  
        <h2 style="color:MidnightBlue; font-style:italic;">  
            c# example - find index of character in string
        <hr width="550" align="left" color="Gainsboro" />  
        <br /><br />
            Text="find index of character in string"  
More c# examples