c# - How to remove characters from a string

Remove characters from a String
The String represents text as a sequence of UTF-16 code units. The String is a sequential collection of characters that is used to represent text. The String is a sequential collection of System.Char objects.

The following .net c# tutorial code demonstrates how we can remove characters from a String instance. So, in this .net c# tutorial code we will remove a specified number of characters from a String object from the specified character position. Here we will use String Remove() method to do this.

The String Remove() method returns a new String in which a specified number of characters from the current String are deleted. The String Remove() method has two overloads.The String Remove(int startIndex) returns a new String in which all the characters in the current instance, beginning at a specified position and continuing through the last position, have been deleted. So using this overload we can delete all the characters from a String after a specified index position.

The String Remove(int startIndex, int count) method overload returns a new String in which a specified number of characters in the current instance beginning at a specified position has been deleted. So using this overload we can delete a specified number of characters from a String instance at the specified index position.
string-remove.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 = "Coconut. Coakum. Coffee Plant. Colic Weed";

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

        //this line get first 7 characters of string and remove other.
        string result = plants.Remove(7);

        //remove 5th character only from string
        string result2 = plants.Remove(5,1);

        Label1.Text += "<br />first 7 characters of string: " + result;
        Label1.Text += "<br />string without 5th character: " + result2;
    }  
</script>  

<html xmlns="http://www.w3.org/1999/xhtml">  
<head id="Head1" runat="server">  
    <title>c# example - string remove</title>  
</head>  
<body>  
    <form id="form1" runat="server">  
    <div>  
        <h2 style="color:MidnightBlue; font-style:italic;">  
            c# example - string remove
        </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 remove"  
            OnClick="Button1_Click"
            Height="40"  
            Font-Bold="true"  
            />  
    </div>  
    </form>  
</body>  
</html>

c# - How to find second occurrence of a substring in a string

Find the second occurrence of a substring within a String
The String represents text as a sequence of UTF-16 code units. The String is a sequential collection of characters that is used to represent text. The String is a sequential collection of System.Char objects.

The following .net c# tutorial code demonstrates how we can find the second occurrence of a substring within a String. In this .net c# tutorial code we will find that a specified substring is exist more than one time inside a String object and we will get the second occurrence index position of the substring.

Such as we have a String instance, we have to find a substring ‘Birch’ within it and we also have to show the index position of the ‘Birch’ substring’s second occurrence on the user interface. The substring maybe exists more than two times within the String instance but we have to find the second occurrence index position of the specified substring within the String instance.

We can do this using a ‘while’ loop. We will loop through all occurrences of the specified substring inside the String instance. When we get the second occurrence of the substring within the String instance, we will collect its index position and show it on the user interface. At that time we also break the loop because our desired result is found.

We can find the index position of the specified substring within a String instance using the String IndexOf() method. The String IndexOf() method reports the zero-based index of the first occurrence of a specified Unicode character or String within this instance. The IndexOf() method returns -1 if the character or String is not found in the instance.

The String IndexOf(string value, int startIndex) method overload reports the zero-based index of the first occurrence of the specified String in this instance and the search starts at a specified character position.
string-find-second-occurrence.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 = "Paper Birch. Red Birch. Bay Laurel. Silver Birch.";

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

        //substring to find/search indexes/occurrences in string.
        string indexOfSubStringToFind = "Birch";

        int index = 0;
        int counter = 0;

        //find all indexes/occurrences of specified substring in string
        while ((index=plants.IndexOf(indexOfSubStringToFind, index)) != -1)
        {
            index++;
            counter++;
            //this line check second occurrence of search substring.
            if (counter == 2)
            {
                Label1.Text += "<br />Second occurrence of [Birch] found at index: " + index;
                break;
            }
        }
    }  
</script>  

<html xmlns="http://www.w3.org/1999/xhtml">  
<head id="Head1" runat="server">  
    <title>c# example - string find second occurrence</title>  
</head>  
<body>  
    <form id="form1" runat="server">  
    <div>  
        <h2 style="color:MidnightBlue; font-style:italic;">  
            c# example - string find second occurrence
        </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 find second occurrence"  
            OnClick="Button1_Click"
            Height="40"  
            Font-Bold="true"  
            />  
    </div>  
    </form>  
</body>  
</html>

c# - How to find all occurrences of a substring within a string

Find all occurrences of a substring within a String
The String represents text as a sequence of UTF-16 code units. The String is a sequential collection of characters that is used to represent text. The String is a sequential collection of System.Char objects.

The following .net c# tutorial code demonstrates how we can find all occurrences of a substring within a String. In this .net c# tutorial code we will find that a specified substring is how many times exists inside a String object. Such as we have a String instance, we have to find a substring ‘Cherry’ within it and we also have to show all the index positions of the ‘Cherry’ substring found within the String instance.

We can do this using a ‘while’ loop. We will loop through all occurrences of the specified substring inside the String instance. The loop will continue until there are no matching available. On the looping time, we also display the substring occurrences index position on the user interface.

We can find the index position of the specified substring within a String instance using the String IndexOf() method. The String IndexOf() method reports the zero-based index of the first occurrence of a specified Unicode character or String within this instance. The IndexOf() method returns -1 if the character or String is not found in the instance.

The String IndexOf(string value, int startIndex) method overload reports the zero-based index of the first occurrence of the specified String in this instance and the search starts at a specified character position.
string-find-all-occurrences.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 = "Black Cherry. Cabinet Cherry. Skunk Cabbage. Wild Cherry";

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

        //substring to find/search indexes/occurrences in string.
        string indexOfSubStringToFind = "Cherry";

        int index = 0;

        Label1.Text += "<br /><br />substring [Cherry] found in following index position in string";

        //find all indexes/occurrences of specified substring in string
        while ((index=plants.IndexOf(indexOfSubStringToFind, index)) != -1)
        {
            Label1.Text += "<br />" + index;
            index++;
        }
    }  
</script>  

<html xmlns="http://www.w3.org/1999/xhtml">  
<head id="Head1" runat="server">  
    <title>c# example - string find all occurrences</title>  
</head>  
<body>  
    <form id="form1" runat="server">  
    <div>  
        <h2 style="color:MidnightBlue; font-style:italic;">  
            c# example - string find all occurrences
        </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 find all occurrences"  
            OnClick="Button1_Click"
            Height="40"  
            Font-Bold="true"  
            />  
    </div>  
    </form>  
</body>  
</html>

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 stringprogrammatically at run time in an asp.net application. .Net framework's String Class represent Text as a series of UnicodeCharacters.

String Class String.IndexOf(Char) overloaded method reports the zero-based index of the first occurrence of the specified Unicode characterin this string. String.IndexOf(Char) method has a required parameter named 'value' which data type is System.Char. This parameter valuerepresent 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 ofspecified 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 andspecify the string instance and a character to search.
find-index-of-character-in-string.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 = "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);
        }
        else
        {
            Label1.Text += "<br />character [V] not found in string";
        }
    }  
</script>  

<html xmlns="http://www.w3.org/1999/xhtml">  
<head id="Head1" runat="server">  
    <title>c# example - find index of character in string</title>  
</head>  
<body>  
    <form id="form1" runat="server">  
    <div>  
        <h2 style="color:MidnightBlue; font-style:italic;">  
            c# example - find index of character in string
        </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="find index of character in string"  
            OnClick="Button1_Click"
            Height="40"  
            Font-Bold="true"  
            />  
    </div>  
    </form>  
</body>  
</html>

c# - How to find index of a substring/character in a string

Find the index of a substring or character in a String
The String represents text as a sequence of UTF-16 code units. The String is a sequential collection of characters that is used to represent text. The String is a sequential collection of System.Char objects.

The following .net c# tutorial code demonstrates how we can find the index of a substring or a character in a String object. So, in this .net c# tutorial code we will find the index position of a specified substring or a specified character within a String instance. Here we will find the index of a substring or a character from a String object using the String IndexOf() method.

The String IndexOf() method reports the zero-based index of the first occurrence of a specified Unicode character or string within this instance. The String IndexOf() method returns -1 if the character or String is not found in this instance.

The String IndexOf(String) method overload reports the zero-based index of the first occurrence of the specified String in this instance. So using this method overload we can find a specified substring’s index position in a String instance. This String IndexOf(String) method returns the index position of the specified substring if it is found in the String instance otherwise it returns -1 if it is not found.

The String IndexOf(Char) method overload reports the zero-based index of the first occurrence of the specified Unicode character in this string. So using this method overload we can find the index position of a specified character from a String instance. This method overload returns the index position of the specified character if it is found in the String instance otherwise it returns -1 if it is not found in the String instance.
string-find-index.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 = "Hard Thistle. Cutleaf Toothwort. Leatherleaf Viburnum";

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

        string indexToFind = "Cutleaf";
        char indexToFind2 = 'T';

        //this line find/search index of a substring in string
        if (plants.IndexOf(indexToFind) != -1)
        {
            Label1.Text += "<br />Cutleaf found in string index of: ";
            Label1.Text += plants.IndexOf(indexToFind);
        }
        else
        {
            Label1.Text += "<br />Cutleaf not found in string";
        }

        //this line find/search index of a character in string
        if (plants.IndexOf(indexToFind2) != -1)
        {
            Label1.Text += "<br />character 'T' found in string index of: ";
            Label1.Text += plants.IndexOf(indexToFind2);
        }
        else
        {
            Label1.Text += "<br />character 'T' not found in string";
        }
    }  
</script>  

<html xmlns="http://www.w3.org/1999/xhtml">  
<head id="Head1" runat="server">  
    <title>c# example - string find index</title>  
</head>  
<body>  
    <form id="form1" runat="server">  
    <div>  
        <h2 style="color:MidnightBlue; font-style:italic;">  
            c# example - string find index
        </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 find index"  
            OnClick="Button1_Click"
            Height="40"  
            Font-Bold="true"  
            />  
    </div>  
    </form>  
</body>  
</html>

c# - How to check whether a string starts with vowel

Check whether a String starts with a vowel
The String represents text as a sequence of UTF-16 code units. The String is a sequential collection of characters that is used to represent text. The String is a sequential collection of System.Char objects.

The following .net c# tutorial code demonstrates how we can check whether a String instance starts with a vowel. So, in this .net c# tutorial code we will determine whether a String object’s first character is a vowel or not. To check that we have to create a char array of all lowercase vowels. Then we will check whether the first character of the String instance is a vowel or not.

The String ToLower() method returns a copy of this String converted to lowercase. So using the ToLower() method we convert the String instance characters to lowercase.

Then we create a char array from the lowercase String instance. The String ToCharArray() method copies the characters in this instance to a Unicode character Array. So using this method we can create a char Array from a String instance.

Next, we will get the first element of the char array. The Enumerable ElementAt() method returns the element at a specified index in a sequence. So using this method we can get the first element of the char Array. The element is a Char object instance.

Finally, we will check whether the retrieved Char instance exists in the vowel char Array or not. If the char Array contains the specified Char instance then the String instance starts with a vowel.

The Enumerable Contains() method determines whether a sequence contains a specified element. So using this method we can determine whether the specified Char instance exists in the vowels Array or not.
string-starts-with-vowel.aspx

<%@ Page Language="C#" AutoEventWireup="true"%>

<!DOCTYPE html>  
<script runat="server"> 
    protected void Button1_Click(object sender, System.EventArgs e)  
    {
        //this section create string variables.
        string stringPlants = "Thimbleweed. Tassel Weed. Sweet Potato.";
        string stringPlants2 = "Orange Coneflower. Yellow Corydalis. White Tansy.";

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

        //this line create a char array.
        char[] vowels = { 'a', 'e', 'i', 'o', 'u' };

        //this line get string first/begin character (lower case)
        char firstCharacter = stringPlants.ToLower().ToCharArray().ElementAt(0);

        //this line get string first/begin character (lower case)
        char firstCharacter2 = stringPlants2.ToLower().ToCharArray().ElementAt(0);

        //test string starts with vowel or not
        Boolean result = vowels.Contains(firstCharacter);
        Boolean result2 = vowels.Contains(firstCharacter2);

        Label1.Text += "<br /><br />stringPlants first character: " + firstCharacter;
        Label1.Text += "<br />stringPlants2 first character: " + firstCharacter2;

        Label1.Text += "<br /><br />stringPlants starts with vowel? " + result.ToString();
        Label1.Text += "<br />stringPlants2 starts with vowel? " + result2.ToString();
    }  
</script>  

<html xmlns="http://www.w3.org/1999/xhtml">  
<head id="Head1" runat="server">  
    <title>c# example - string starts with vowel</title>  
</head>  
<body>  
    <form id="form1" runat="server">  
    <div>  
        <h2 style="color:MidnightBlue; font-style:italic;">  
            c# example - string starts with vowel
        </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 starts with vowel"  
            OnClick="Button1_Click"
            Height="40"  
            Font-Bold="true"  
            />  
    </div>  
    </form>  
</body>  
</html>

c# - String startswith case insensitive

String startswith case insensitive
The following asp.net c# example code demonstrate us how can we determine whether a string starts with a specifiedsubstring (string comparison is ignoring case) programmatically at run time in an asp.net application.

.Net framework's String Class String.StartsWith(String, StringComparison) overloaded method can determine whether thebeginning of this string instance matches the specified string when compared using the specified comparison option.

String.StartsWith(String, StringComparison) method has two required parameters named 'value' and 'comparisonType'. The 'value' parameterrepresent the string to compare. The 'comparisonType' parameter value type is 'System.StringComparison' which represent one of the enumerationvalues that determines how this string and specified string (value parameter) are compared.

System.StringComparison enumeration value 'OrdinalIgnoreCase' allow us to compare strings using ordinal sort rules and ignoring the case(case insensitive) of the strings being compared.

This method return a Boolean value. It return 'true', if this instance begins with 'value' parameter value; otherwise it return 'false'.

So, we can check whether a string begins with specified substring by ignoring case in this wayString.StartsWith(String, StringComparison.OrdinalIgnoreCase)
string-startswith-case-insensitive.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 stringPlants = "Coffee Plant. Eastern Coneflower. Pale Corydalis";

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

        string wordToCheck = "Coffee";
        string wordToCheck2 = "Coneflower";
        string wordToCheck3 = "CoFFee";

        //this line check string starts with/begin with 'Coffee' or not / ignore case
        Boolean result = stringPlants.StartsWith(wordToCheck, StringComparison.OrdinalIgnoreCase);

        //this line check string starts with/ begin with 'Coneflower' or not / ignore case
        Boolean result2 = stringPlants.StartsWith(wordToCheck2, StringComparison.OrdinalIgnoreCase);

        //this line check string starts with/begin with 'CoFFee' or not / ignore case
        Boolean result3 = stringPlants.StartsWith(wordToCheck3, StringComparison.OrdinalIgnoreCase);

        Label1.Text += "<br /><br /> string starts with [Coffee] ignore case? " + result.ToString();
        Label1.Text += "<br />string starts with [Coneflower]? ignore case" + result2.ToString();
        Label1.Text += "<br />string starts with [CoFFee] ignore case? " + result3.ToString();
    }  
</script>  

<html xmlns="http://www.w3.org/1999/xhtml">  
<head id="Head1" runat="server">  
    <title>c# example - string startswith case insensitive</title>  
</head>  
<body>  
    <form id="form1" runat="server">  
    <div>  
        <h2 style="color:MidnightBlue; font-style:italic;">  
            c# example - string startswith case insensitive
        </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 startswith case insensitive"  
            OnClick="Button1_Click"
            Height="40"  
            Font-Bold="true"  
            />  
    </div>  
    </form>  
</body>  
</html>

c# - How to check whether a string starts with letter

String starts with letter
The following asp.net c# example code demonstrate us how can we determine whether a string starts with a letterprogrammaticaly at run time in an asp.net application. .Net framework's String Class represent text as a series of Unicodecharacters. String Class has no direct method or property to determine whether a string begins with a letter (a to z).

First, we need to get the first character of a string object to verify it is a letter or not. String.ElementAt()method allow us to get the character at a specified index position from a string. So, we can get the first character of a stringby calling the ElementAt() method as this way String.ElementAt(0), because string object is zero-based index.

Char.IsLetter(Char) overloaded method indicate whether the specified Unicode character is categorized as a Unicode letter.So, we can determine the previously collected first character of a string is a letter or not by accessing the Char.IsLetter(Char)method.

Finally, we can determine whether string starts with a letter by this way String.ElementAt(0).IsLetter(). If it return'true' then string starts with letter; otherwise string is not starts with letter.
string-starts-with-letter.aspx

<%@ Page Language="C#" AutoEventWireup="true"%>

<!DOCTYPE html>  
<script runat="server"> 
    protected void Button1_Click(object sender, System.EventArgs e)  
    {
        //this section create string variables.
        string stringPlants = "1. Swamp Holly 2. Winterberry Holly";
        string stringPlants2 = "Horse Cane. Indian Paintbrush";

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

        //this line get string first/begin character
        char firstCharacter = stringPlants.ToCharArray().ElementAt(0);

        //this line get string first/begin character
        char firstCharacter2 = stringPlants2.ToCharArray().ElementAt(0);

        //test character is letter or not
        Boolean isCharacterLetter = char.IsLetter(firstCharacter);
        Boolean isCharacterLetter2 = char.IsLetter(firstCharacter2);

        Label1.Text += "<br /><br />stringPlants first character: " + firstCharacter;
        Label1.Text += "<br />stringPlants2 first character: " + firstCharacter2;

        Label1.Text += "<br /><br />stringPlants starts with letter? " + isCharacterLetter.ToString();
        Label1.Text += "<br />stringPlants2 starts with letter? " + isCharacterLetter2.ToString();
    }  
</script>  

<html xmlns="http://www.w3.org/1999/xhtml">  
<head id="Head1" runat="server">  
    <title>c# example - string starts with letter</title>  
</head>  
<body>  
    <form id="form1" runat="server">  
    <div>  
        <h2 style="color:MidnightBlue; font-style:italic;">  
            c# example - string starts with letter
        </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 starts with letter"  
            OnClick="Button1_Click"
            Height="40"  
            Font-Bold="true"  
            />  
    </div>  
    </form>  
</body>  
</html>

c# - How to check whether a string ends with a number

Check whether a String ends with a number
The String represents text as a sequence of UTF-16 code units. The String is a sequential collection of characters that is used to represent text. The String is a sequential collection of System.Char objects.

The following .net c# tutorial code demonstrates how we can check whether a String ends with a number. In this .net c# tutorial we will determine whether a String’s last character is a number or not.

The String ToCharArray() method copies the characters in this instance to a Unicode character array. So, we can convert a String to a char array. The ElementAt() method allows us to get the item from a specified index position. This way, we get the last character of a String instance.

The Char IsDigit() method indicates whether a Unicode character is categorized as a decimal digit. We have to pass a Char object to this IsDigit(Char) method to check this provided Char is a digit or not. This method returns true if the provided Character is a decimal digit otherwise false.

The Char IsNumber() method indicates whether a Unicode character is categorized as a number. We have to pass a Unicode character to this method. This IsNumber(Char) method returns true if the provided character is a number otherwise false.
string-endswith-number.aspx

<%@ Page Language="C#" AutoEventWireup="true"%>

<!DOCTYPE html>  
<script runat="server"> 
    protected void Button1_Click(object sender, System.EventArgs e)  
    {
        //this section create string variables.
        string stringPlants = "Extinguisher Moss. Eytelia";
        string stringPlants2 = "Coast Polypody 5";

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

        //this line get string end/last character
        char stringLastCharacter = stringPlants.ToCharArray().ElementAt(stringPlants.Length - 1);

        //this line get string end/last character
        char stringLastCharacter2 = stringPlants2.ToCharArray().ElementAt(stringPlants2.Length - 1);

        Boolean result = char.IsNumber(stringLastCharacter);
        Boolean result2 = char.IsNumber(stringLastCharacter2);

        //another option to test character number or letter
        //Boolean result = char.IsDigit(stringLastCharacter);
        //Boolean result2 = char.IsDigit(stringLastCharacter2);

        Label1.Text += "<br /><br />stringPlants last character: " + stringLastCharacter;
        Label1.Text += "<br />stringPlants2 last character: " + stringLastCharacter2;

        Label1.Text += "<br /><br />stringPlants ends with number? " + result.ToString();
        Label1.Text += "<br />stringPlants2 ends with number? " + result2.ToString();
    }  
</script>  

<html xmlns="http://www.w3.org/1999/xhtml">  
<head id="Head1" runat="server">  
    <title>c# example - string endswith number</title>  
</head>  
<body>  
    <form id="form1" runat="server">  
    <div>  
        <h2 style="color:MidnightBlue; font-style:italic;">  
            c# example - string endswith number
        </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 endswith number"  
            OnClick="Button1_Click"
            Height="40"  
            Font-Bold="true"  
            />  
    </div>  
    </form>  
</body>  
</html>

c# - String endswith ignorecase

String ends with ignore case
The String represents text as a sequence of UTF-16 code units. The String is a sequential collection of characters that is used to represent text. The String is a sequential collection of System.Char objects.

The following .net c# tutorial code demonstrates how we can determine whether a String instance ends with a specified String while we compare by ignoring the case. So, in this .net c# tutorial code we will check whether a String object ends with a specified String by ignoring the case. Here we will compare it using the String EndsWith() method.

The String EndsWith() method determines whether the end of this String instance matches a specified String. The String EndsWith(String, StringComparision) method overload determines whether the end of this String instance matches the specified String when compared using the specified comparison option.

The String EndsWith(string value, StringComparision comparisonType) method has two parameters. The value parameter is the String to compare to the substring at the end of this instance. For the comparisonType parameter, we will pass the StringComparison.OrdinalIgnoreCase value. The OrdinalIgnoreCase compares strings using ordinal (binary) sort rules and ignoring the case of the strings being compared.

So, finally using this String EndsWith(string value, StringComparision comparisonType) method .net c# developers can determine whether a String instance ends with a specified String by ignoring the case.
string-endswith-ignorecase.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 stringPlants = "Goldenglow. Winter Gilliflower. Harlequin. Goldenglow";

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

        string wordToCheck = "Goldenglow";
        string wordToCheck2 = "GoldenGLOW";
        string wordToCheck3 = "Winter";

        //this line check string ends with 'Goldenglow' or not / ignore case
        Boolean result = stringPlants.EndsWith(wordToCheck, StringComparison.OrdinalIgnoreCase);

        //this line check string ends with 'GoldenGLOW' or not / ignore case
        Boolean result2 = stringPlants.EndsWith(wordToCheck2, StringComparison.OrdinalIgnoreCase);

        //this line check string ends with 'Winter' or not / ignore case
        Boolean result3 = stringPlants.EndsWith(wordToCheck3, StringComparison.OrdinalIgnoreCase);

        Label1.Text += "<br /><br /> string ends with [Goldenglow] ignore case? " + result.ToString();
        Label1.Text += "<br />string ends with [GoldenGLOW]? ignore case" + result2.ToString();
        Label1.Text += "<br />string ends with [Winter] ignore case? " + result3.ToString();
    }  
</script>  

<html xmlns="http://www.w3.org/1999/xhtml">  
<head id="Head1" runat="server">  
    <title>c# example - string endswith ignorecase</title>  
</head>  
<body>  
    <form id="form1" runat="server">  
    <div>  
        <h2 style="color:MidnightBlue; font-style:italic;">  
            c# example - string endswith ignorecase
        </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 endswith ignorecase"  
            OnClick="Button1_Click"
            Height="40"  
            Font-Bold="true"  
            />  
    </div>  
    </form>  
</body>  
</html>

c# - How to check whether a string starts with specific substring

Check whether a String starts with a specific substring
The String represents text as a sequence of UTF-16 code units. The String is a sequential collection of characters that is used to represent text. The String is a sequential collection of System.Char objects.

The following .net c# tutorial code demonstrates how we can check whether a String instance starts with a specific substring. In this .net c# tutorial code we will check whether a String object starts with a specific substring or not by using the String StartsWith() method.

The String StartsWith(String) method overload determines whether the beginning of this String instance matches the specified String. So using this String StartsWith(string value) method overload .net developers can determine whether a String instance starts with a specific substring or not.

The String StartsWith(string value) method overload has a required parameter named value whose data type is a string. The value parameter is the String to compare. This method returns a Boolean value. It returns true if the value matches the beginning of this String otherwise the method returns false. The String StartsWith(string value) method overload throws ArgumentNullException if the provided value is null.
string-starts-with.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 stringPlants = "Boston Fern. Water Fern. European Flax. Wild Garli.";

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

        string stringStartsWith = "European";
        string stringStartsWith2 = "Boston";

        //this line check string starts with/ begins with 'European' or not
        Boolean result = stringPlants.StartsWith(stringStartsWith);

        //this line check string end with/ begins with 'Boston' or not
        Boolean result2 = stringPlants.StartsWith(stringStartsWith2);

        Label1.Text += "<br /><br /> string starts with [European]? " + result.ToString();
        Label1.Text += "<br /><br /> string starts with [Boston]? " + result2.ToString();
    }  
</script>  

<html xmlns="http://www.w3.org/1999/xhtml">  
<head id="Head1" runat="server">  
    <title>c# example - string starts with</title>  
</head>  
<body>  
    <form id="form1" runat="server">  
    <div>  
        <h2 style="color:MidnightBlue; font-style:italic;">  
            c# example - string starts with
        </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 starts with"  
            OnClick="Button1_Click"
            Height="40"  
            Font-Bold="true"  
            />  
    </div>  
    </form>  
</body>  
</html>

c# - How to check whether a string ends with specific substring

Check whether a String ends with a specific substring
The String represents text as a sequence of UTF-16 code units. The String is a sequential collection of characters that is used to represent text. The String is a sequential collection of System.Char objects.

The following .net c# tutorial code demonstrates how we can check whether a String instance ends with a specific substring. In this .net c# tutorial code we will check whether a String object ends with a specific substring or not by using the String EndsWith() method.

The String EndsWith() method determines whether the end of this String instance matches a specified String. The String EndsWith(String) method overload determines whether the end of this String instance matches the specified String. So using this String EndsWith(string value) method overload .net developers can determine whether a String instance ends with a specific substring or not.

The String EndsWith(string value) method overload has a required parameter named value whose data type is a string. The value parameter is the string to compare to the substring at the end of this instance. This method returns a Boolean value. The String EndsWith(string value) method returns true if the value matches the end of this instance otherwise the method returns false. The String EndsWith(string value) method overload throws ArgumentNullException if the provided value is null.
string-ends-with.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 stringPlants = "Spring Cress, Upland Cress, Flowering Dogwood";

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

        string wordToCheck = "Dogwood";
        string wordToCheck2 = "Plague";

        //this line check string end with 'Dogwood' or not
        Boolean result = stringPlants.EndsWith(wordToCheck);
        //this line check string end with 'Plague' or not
        Boolean result2 = stringPlants.EndsWith(wordToCheck2);

        Label1.Text += "<br /><br /> string ends with [Dogwood]? " + result.ToString();
        Label1.Text += "<br /><br /> string ends with [Plague]? " + result2.ToString();
    }  
</script>  

<html xmlns="http://www.w3.org/1999/xhtml">  
<head id="Head1" runat="server">  
    <title>c# example - string ends with</title>  
</head>  
<body>  
    <form id="form1" runat="server">  
    <div>  
        <h2 style="color:MidnightBlue; font-style:italic;">  
            c# example - string ends with
        </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 ends with"  
            OnClick="Button1_Click"
            Height="40"  
            Font-Bold="true"  
            />  
    </div>  
    </form>  
</body>  
</html>

c# - How to escape double quotes in a string

String escape double quote
The following asp.net c# example code demonstrate us how can we escape double quote in a string programmaticallyat run time in an asp.net application. .Net framework's String Class represent text as a series of Unicode characters.We can escape double quotes (") in a string by several ways.

We can escape double quotes in a string by using a escape character Backslash (\). If we want to include a doublequotes in this way, we should write the string as ("a \"sample\" text"). Here the word (sample) will be surrounded by twodouble quotes as "sample".

We also can escape double quotes in a string object by using @ symbol. If we want to write the same string in this technique,then we should format it as (@"a ""sample"" text"). Here we also need to place a double quotes two times to get output a single doublequotes. Both techniques show the same output.
string-escape-double-quote.aspx

<%@ Page Language="C#" AutoEventWireup="true"%>

<!DOCTYPE html>  
<script runat="server"> 
    protected void Button1_Click(object sender, System.EventArgs e)  
    {
        //this section create string variable with double quote.
        string stringPlants = "\"Brown Betty\" \"Meadow Cabbage\" \"Swamp Cabbage\"";

        //another way to escape double quote in string
        string stringPlants2 = @"""California Sycamore"" ""California Walnut"" ""Canada Root""";

        Label1.Text = "string of plants..................<br />";
        Label1.Text += stringPlants;
        Label1.Text += "<br />"+stringPlants2;
    }  
</script>  

<html xmlns="http://www.w3.org/1999/xhtml">  
<head id="Head1" runat="server">  
    <title>c# example - string escape double quote</title>  
</head>  
<body>  
    <form id="form1" runat="server">  
    <div>  
        <h2 style="color:MidnightBlue; font-style:italic;">  
            c# example - string escape double quote
        </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 escape double quote"  
            OnClick="Button1_Click"
            Height="40"  
            Font-Bold="true"  
            />  
    </div>  
    </form>  
</body>  
</html>

c# - String equals case insensitive

Check whether two Strings are equal by case-insensitive comparison
The String represents text as a sequence of UTF-16 code units. The String is a sequential collection of characters that is used to represent text. The String is a sequential collection of System.Char objects.

The following .net c# tutorial code demonstrates how we can check whether two String instances are equal when we ignore the case while comparing the String instances. So in this .net c# tutorial code example, we will check whether two String objects have the same value or not in a case-insensitive comparison way. The .net c# developers can check the two String object’s equality by using the String Equals() method.

The String Equals() method determines whether two String objects have the same value. The String Equals(String, StringComparison) method overload determines whether this String and a specified String object have the same value. The second parameter specifies the culture, case, and sort rules used in the comparison. So using this method overload we can compare two String instance equality by ignoring the case.

The String Equals(string? value, StringComparison comparisonType) method overload has two parameters. The value parameter is the String to compare to this instance. And the comparisonType parameter is one of the enumeration values that specifies how the Strings will be compared. Here we passed StringComparison.OrdinalIgnoreCase value for the comparisonType parameter to ignore the case while comparing two String instances.

The String Equals(String, StringComparison) method returns a Boolean value. It returns true if the value of the value parameter is the same as this String otherwise the method returns false. The method overload throws ArgumentException if the comparisonType parameter value is not a StringComparison value.

Finally, we can check whether two String instances are equal or not while comparing them in a case-insensitive way by using the String Equals(String, StringComparison) method overload.
string-equals-case-insensitive.aspx

<%@ Page Language="C#" AutoEventWireup="true"%>

<!DOCTYPE html>  
<script runat="server"> 
    protected void Button1_Click(object sender, System.EventArgs e)  
    {
        //this section create string variables.
        string stringPlants = "Cutleaf Coneflower";
        string stringPlants2 = "CUTLEAF Coneflower";
        string stringPlants3 = "Golden Corydalis";

        Label1.Text = "string of plants..................<br />";
        Label1.Text += "stringPlants: " + stringPlants;
        Label1.Text += "<br />stringPlants2: " + stringPlants2;
        Label1.Text += "<br />stringPlants3: " + stringPlants3;

        //this line test two string equality.
        Boolean result1 = stringPlants.Equals(stringPlants2);

        //this line test two string equality ignore case.
        Boolean result1IgnoreCase = stringPlants.Equals(stringPlants2, StringComparison.OrdinalIgnoreCase);

        Boolean result2 = stringPlants.Equals(stringPlants3);

        Label1.Text += "<br /><br />stringPlants equal to stringPlants2...........?" + result1;
        Label1.Text += "<br /><br />stringPlants equal to stringPlants2(ignore case)...........?" + result1IgnoreCase;
        Label1.Text += "<br /><br />stringPlants equal to stringPlants3...........?" + result2;
    }  
</script>  

<html xmlns="http://www.w3.org/1999/xhtml">  
<head id="Head1" runat="server">  
    <title>c# example - string equals case insensitive</title>  
</head>  
<body>  
    <form id="form1" runat="server">  
    <div>  
        <h2 style="color:MidnightBlue; font-style:italic;">  
            c# example - string equals case insensitive
        </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 equals case insensitive"  
            OnClick="Button1_Click"
            Height="40"  
            Font-Bold="true"  
            />  
    </div>  
    </form>  
</body>  
</html>

c# - How to append a char to a string

Append a Char to a String
The String represents text as a sequence of UTF-16 code units. The String is a sequential collection of characters that is used to represent text. The String is a sequential collection of System.Char objects.

The following .net c# tutorial code demonstrates how we can append a Char to a String. In this .net c# tutorial code we will append a Char object to a String object. Here we will append a Char ‘L’ to the String using the String Insert() method and we also add a Char to the String instance using a plus operator.

The Char represents a character as a UTF-16 code unit. We can simply append a Char instance to a String object by a plus operator. The plus operator adds the specified Char object at the end of the specified String instance. The result also returns a String object.

The String Insert() method returns a new String in which a specified String is inserted at a specified index position in the instance. So using the String Insert(int startIndex, string value) method we can append a Char object to the String instance.

We have to convert the Char object to a String object and we also pass the length of the String for the startIndex parameter. So, the method returns a String instance where the specified Char object is appended to the source String. The Insert() method throws ArgumentNullException if the value is null. It also throws ArgumentOutOfRangeException if the startIndex is negative or greater than the length of this instance.
string-append-char.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 stringOfChars = "ABCDEFGHIJK";

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

        //this line create a char variable with value 'L'
        Char c = 'L';

        //this line append character 'L' on string (insert at string last)
        stringOfChars = stringOfChars.Insert(stringOfChars.Length,c.ToString());

        //another way to append character on string
        //stringOfChars += c;

        Label1.Text += "<br /><br />string after append char 'L'...........<br />";
        Label1.Text += stringOfChars;
    }  
</script>  

<html xmlns="http://www.w3.org/1999/xhtml">  
<head id="Head1" runat="server">  
    <title>c# example - string append char</title>  
</head>  
<body>  
    <form id="form1" runat="server">  
    <div>  
        <h2 style="color:MidnightBlue; font-style:italic;">  
            c# example - string append char
        </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 append char"  
            OnClick="Button1_Click"
            Height="40"  
            Font-Bold="true"  
            />  
    </div>  
    </form>  
</body>  
</html>

c# - How to append a substring to a string

Append a substring to a String
The String represents text as a sequence of UTF-16 code units. The String is a sequential collection of characters that is used to represent text. The String is a sequential collection of System.Char objects.

The following .net c# tutorial code demonstrates how we can append a substring to a String. In this .net c# tutorial code we will append a substring to a String object. Here we will append a substring ‘ Laceflower.’ to the String instance using the String Insert() method and we also add a substring to the String instance using a plus operator.

We can simply append a substring to a String object by a plus operator. The plus operator adds the specified substring at the end of the specified String instance. The result also returns a String object.

The String Insert() method returns a new String in which a specified String is inserted at a specified index position in the instance. So using the String Insert(int startIndex, string value) method we can append a substring to the String instance.

We have to pass the length of the String instance for the startIndex parameter and the substring for the value parameter. So, the method returns a String object where the specified substring is appended to the source String. The Insert() method throws ArgumentNullException if the value is null. It also throws ArgumentOutOfRangeException if the startIndex is negative or greater than the length of this instance.
string-append.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 stringPlants = "Inkberry. Juneberry. Kousa. Kudzu.";

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

        //this line append plant 'Laceflower' in string (insert at string last)
        stringPlants = stringPlants.Insert(stringPlants.Length, " Laceflower.");

        //another way to append string
        //stringPlants += " Laceflower.";

        Label1.Text += "<br /><br />string after append ' Laceflower.'...........<br />";
        Label1.Text += stringPlants;
    }  
</script>  

<html xmlns="http://www.w3.org/1999/xhtml">  
<head id="Head1" runat="server">  
    <title>c# example - string append</title>  
</head>  
<body>  
    <form id="form1" runat="server">  
    <div>  
        <h2 style="color:MidnightBlue; font-style:italic;">  
            c# example - string append
        </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 append"  
            OnClick="Button1_Click"
            Height="40"  
            Font-Bold="true"  
            />  
    </div>  
    </form>  
</body>  
</html>

c# - How to check whether a string contains any special character

Check whether a String contains any special character
The String represents text as a sequence of UTF-16 code units. The String is a sequential collection of characters that is used to represent text. The String is a sequential collection of System.Char objects.

The following .net c# tutorial code demonstrates how we can check whether a String object contains any special character. In this .net c# tutorial code we will determine whether a String instance contains any special character. Here we do this using regular expressions.

The Regex represents an immutable regular expression. The Regex() initializes a new instance of the Regex class. The Regex(String, RegexOptions) constructor initializes a new instance of the Regex class for the specified regular expression with options that modify the pattern.

So, using the Regex(String pattern, RegexOptions options) method we can check whether a String object contains any special character or not. We have to pass the specified regular expression to the method as the pattern. We also pass the RegexOptions.IgnoreCase for the options parameter.

The Regex IsMatch() method indicates whether the regular expression finds a match in the input String. This method returns a Boolean value. It returns true if the regular expression finds a match otherwise it returns false.
string-contains-special-characters.aspx

<%@ Page Language="C#" AutoEventWireup="true"%>

<!DOCTYPE html>  
<script runat="server"> 
    protected void Button1_Click(object sender, System.EventArgs e)  
    {
        //this section create string variables.
        string colors = "1 Red 2 green 3 blue";
        string colors2 = "#red #green #blue";
        string colors3 = "red* green* blue*";

        Label1.Text = "string..................<br />";
        Label1.Text += "colors: " + colors;
        Label1.Text += "<br />colors2: " + colors2;
        Label1.Text += "<br />colors3: " + colors3;

        //check string contains any special characters without space
        Regex rex = new Regex("^[a-z0-9 ]+$",RegexOptions.IgnoreCase);

        Boolean result = rex.IsMatch(colors);
        Boolean result2 = rex.IsMatch(colors2);
        Boolean result3 = rex.IsMatch(colors3);

        Label1.Text += "<br /><br />colors contains no special characters without space? " + result.ToString();
        Label1.Text += "<br /><br />colors2 contains no special characters without space? " + result2.ToString();
        Label1.Text += "<br /><br />colors3 contains no special characters without space? " + result3.ToString();
    }  
</script>  

<html xmlns="http://www.w3.org/1999/xhtml">  
<head id="Head1" runat="server">  
    <title>c# example - string contains special characters</title>  
</head>  
<body>  
    <form id="form1" runat="server">  
    <div>  
        <h2 style="color:MidnightBlue; font-style:italic;">  
            c# example - string contains special characters
        </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 contains special characters"  
            OnClick="Button1_Click"
            Height="40"  
            Font-Bold="true"  
            />  
    </div>  
    </form>  
</body>  
</html>

c# - How to check whether a string contains numbers only

Check whether a String contains numbers only
The String represents text as a sequence of UTF-16 code units. The String is a sequential collection of characters that is used to represent text. The String is a sequential collection of System.Char objects.

The following .net c# tutorial code demonstrates how we can determine whether a String instance contains numbers only. So, in this .net c# tutorial code we will determine whether a String object’s all characters are digits/numbers or not.

The Enumerable All() method determines whether all elements of a sequence satisfy a condition. So using the Enumerable All() method we can check all the characters of a String instance are digits or not. If all the characters of the String object are digits then we can determine that the String instance contains numbers only.

The Enumerable All() returns a Boolean value. It returns true if every element of the source sequence passes the test in the specified predicate, or if the sequence is empty otherwise this method returns false.

The Enumerable All() method throws ArgumentNullException if the source or predicate is null. So, finally using this Enumerable All() method we can determine whether a String contains numbers only or not.
string-contains-numbers-only.aspx

<%@ Page Language="C#" AutoEventWireup="true"%>

<!DOCTYPE html>  
<script runat="server"> 
    protected void Button1_Click(object sender, System.EventArgs e)  
    {
        //this section create string variables.
        string stringValue = "this is a sample 5 string 7 with number";
        string stringNumbers = "123456789502";

        Label1.Text = "string..................<br />";
        Label1.Text += "stringValue: " + stringValue;
        Label1.Text += "<br />stringNumbers: " + stringNumbers;

        //this line check string contains only digit/numeric value/number or not.
        Boolean isNumeric = stringValue.All(char.IsDigit);

        //this line check string contains only digit/numeric value/number or not.
        Boolean isNumeric2 = stringNumbers.All(char.IsDigit);

        Label1.Text += "<br /><br />stringValue contains only number (digit, numeric value)?.........";
        Label1.Text += isNumeric.ToString();

        Label1.Text += "<br /><br />stringNumbers contains only number (digit, numeric value)?...........";
        Label1.Text += isNumeric2.ToString();
    }  
</script>  

<html xmlns="http://www.w3.org/1999/xhtml">  
<head id="Head1" runat="server">  
    <title>c# example - string contains numbers only</title>  
</head>  
<body>  
    <form id="form1" runat="server">  
    <div>  
        <h2 style="color:MidnightBlue; font-style:italic;">  
            c# example - string contains numbers only
        </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 contains numbers only"  
            OnClick="Button1_Click"
            Height="40"  
            Font-Bold="true"  
            />  
    </div>  
    </form>  
</body>  
</html>

c# - How to check whether a string contains at least one number

Check String contains at least a number
The String represents text as a sequence of UTF-16 code units. The String is a sequential collection of characters that is used to represent text. The String is a sequential collection of System.Char objects.

The following .net c# tutorial code demonstrates how we can check whether a String object contains at least a number. In this .net c# tutorial code we will determine whether a String instance contains at least a number or digit. Here we check this using the Enumerable Any() method.

The Enumerable Any() method determines whether any element of a sequence exists or satisfies a condition. So using this Any() method we test each character of the String object that which character is a digit. If it finds an element is a digit then it returns true otherwise it returns false. In this way, we can determine whether a String object contains at least a number/digit or not.

The Enumerable Any() method returns true if the source sequence is not empty and at least one of its elements passes the test in the specified predicate otherwise it returns false. The Any() method throws ArgumentNullException if the source or predicate is null.
string-contains-numbers.aspx

<%@ Page Language="C#" AutoEventWireup="true"%>

<!DOCTYPE html>  
<script runat="server"> 
    protected void Button1_Click(object sender, System.EventArgs e)  
    {
        //this section create string variables.
        string stringVal = "this is a sample string without number";
        string stringWithNumber = "this is a sample 3 string 7 with number 5";

        Label1.Text = "string..................<br />";
        Label1.Text += "stringVal: " + stringVal;
        Label1.Text += "<br />stringWithNumber: " + stringWithNumber;

        //this line check string contains any digit/numeric value/number.
        Boolean result = stringVal.Any(char.IsDigit);

        //this line check string contains any digit/numeric value/number.
        Boolean result2 = stringWithNumber.Any(char.IsDigit);

        Label1.Text += "<br /><br />stringVal contains any number (digit, numeric value)?.........";
        Label1.Text += result.ToString();

        Label1.Text += "<br /><br />stringWithNumber contains any number (digit, numeric value)?...........";
        Label1.Text += result2.ToString();
    }  
</script>  

<html xmlns="http://www.w3.org/1999/xhtml">  
<head id="Head1" runat="server">  
    <title>c# example - string contains numbers</title>  
</head>  
<body>  
    <form id="form1" runat="server">  
    <div>  
        <h2 style="color:MidnightBlue; font-style:italic;">  
            c# example - string contains numbers
        </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 contains numbers"  
            OnClick="Button1_Click"
            Height="40"  
            Font-Bold="true"  
            />  
    </div>  
    </form>  
</body>  
</html>

c# - How to check whether a string contains a specific character

Check whether a String contains a specific character
The String represents text as a sequence of UTF-16 code units. The String is a sequential collection of characters that is used to represent text. The String is a sequential collection of System.Char objects.

The following .net c# tutorial code demonstrates how we can check whether a String instance contains a specific character. In this .net c# tutorial code we will determine whether a String instance contains a specific character or not. Here we will check the specific character’s existence within a String instance by using the String Contains() method.

The String Contains(Char) method overload returns a value indicating whether a specified character occurs within this string. The String Contains(char value) method has a required parameter named value. The value parameter is the character to seek.

The String Contains() method returns a Boolean value. This method returns true if the value parameter occurs within this string otherwise it returns false. So using this String Contains(Char) method overload the .net c# developers can determine whether a String instance contains a specific character or not.
string-contains-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 stringVal = "abcd efgh ijkl mnop";

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

        //this line check string contains character 'b' or not.
        Boolean resultb = stringVal.Contains('b');

        //this line check string exists character 'z' or not.
        Boolean resultz = stringVal.Contains('z');

        Label1.Text += "<br /><br />string contains character ('b')?.........";
        Label1.Text += resultb.ToString();

        Label1.Text += "<br /><br />string contains character ('z')?...........";
        Label1.Text += resultz.ToString();
    }  
</script>  

<html xmlns="http://www.w3.org/1999/xhtml">  
<head id="Head1" runat="server">  
    <title>c# example - string contains character</title>  
</head>  
<body>  
    <form id="form1" runat="server">  
    <div>  
        <h2 style="color:MidnightBlue; font-style:italic;">  
            c# example - string contains 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 contains character"  
            OnClick="Button1_Click"
            Height="40"  
            Font-Bold="true"  
            />  
    </div>  
    </form>  
</body>  
</html>

c# - How to replace first occurrence of a substring within a string

Replace the first occurrence of a substring within a String
The String represents text as a sequence of UTF-16 code units. The String is a sequential collection of characters that is used to represent text. The String is a sequential collection of System.Char objects.

The following .net c# tutorial code demonstrates how we can replace the first occurrence of a substring within a String instance. So, in this .net c# tutorial code we will find the first occurrence of a substring within a String instance and replace this substring with another specified String.

Such as we have a String object where the ‘white’ substring exists multiple times in it. We have to replace only the first occurrence of the substring ‘white’ with another specified String ‘pink’ within the source String instance.

The Regex represents an immutable regular expression. The Regex() initializes a new instance of the Regex class. The Regex(String, RegexOptions) constructor initializes a new instance of the Regex class for the specified regular expression with options that modify the pattern.

The Regex(String pattern, RegexOptions options) method helps us to construct a Regex instance to find the first occurrence of a specified substring within a String instance and replace it with another String object. We have to pass the specified regular expression to the method as the pattern. We also pass the RegexOptions.IgnoreCase for the options parameter.

The Regex Replace() method replaces strings that match a regular expression pattern with a specified replacement String within a String instance.

The Regex(string input, string replacement, int count) method overload replaces a specified maximum number of Strings that match a regular expression pattern with a specified replacement String within the String instance. So, using this Replace(String, String, Int32) method we can replace the first occurrence of a substring with another String object within a String instance.
string-replace-first.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 stringValue = "White gary red green white DarkBlue white";

        Label1.Text = "string..................<br />";
        Label1.Text += stringValue.ToString();

        //ignore case string replace using Regex
        Regex rex = new Regex("white", RegexOptions.IgnoreCase);

        // this line only replace first occurence of 'white'
        string returnString = rex.Replace(stringValue, "pink",1);

        Label1.Text += "<br /><br />replaced string (first occurence of 'white')........";
        Label1.Text += "<br />" + returnString.ToString();
    }  
</script>  

<html xmlns="http://www.w3.org/1999/xhtml">  
<head id="Head1" runat="server">  
    <title>c# example - string replace first</title>  
</head>  
<body>  
    <form id="form1" runat="server">  
    <div>  
        <h2 style="color:MidnightBlue; font-style:italic;">  
            c# example - string replace first
        </h2>  
        <hr width="550" align="left" color="Gainsboro" />  
        <asp:Label   
            ID="Label1"   
            runat="server"  
            Font-Size="X-Large"
            >  
        </asp:Label>  
        <br /><br />
        <asp:Button   
            ID="Button1"   
            runat="server"   
            Text="string replace first"  
            OnClick="Button1_Click"
            Height="40"  
            Font-Bold="true"  
            />  
    </div>  
    </form>  
</body>  
</html>

c# - How to format a string to a fixed length string

Format a String to a fixed length String
The String represents text as a sequence of UTF-16 code units. The String is a sequential collection of characters that is used to represent text. The String is a sequential collection of System.Char objects.

The following .net c# tutorial code demonstrates how we can format a String to a fixed-length String. In this .net c# tutorial code, we will format a small String instance to a fixed-length big String instance. Such as if the String length is five then we will format it to fifteen characters length. For the remaining extra length, we put specified characters.

The String PadLeft() method returns a new String of a specified length in which the beginning of the current String is padded with spaces or with a specified Unicode character.

The String PadLeft(int totalWidth, char paddingChar) method returns a new String that right-aligns the characters in the instance by padding them on the left with a specified Unicode character, for a specified total length. So, using this method overload, we can format a String instance to a fixed-length String. This method throws ArgumentOutOfRangeException if the ‘totalWidth’ is less than zero.
string-format-fixed-length.aspx

<%@ Page Language="C#" AutoEventWireup="true"%>

<!DOCTYPE html>  
<script runat="server"> 
    protected void Button1_Click(object sender, System.EventArgs e)  
    {
        //this line create a string variable.
        string stringValue = "red";
        string stringValue2 = "green";
        string stringValue3 = "yellow";
        string stringValue4 = "crimson";
        string stringValue5 = "indianred";

        Label1.Text = "string value: " + stringValue.ToString();
        Label1.Text += "<br />string value2: " + stringValue2.ToString();
        Label1.Text += "<br />string value3: " + stringValue3.ToString();
        Label1.Text += "<br />string value4: " + stringValue4.ToString();
        Label1.Text += "<br />string value5: " + stringValue5.ToString();

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

        //make string fixed length 25
        Label1.Text += stringValue.PadLeft(25, '-');
        Label1.Text += "<br />";
        Label1.Text += stringValue2.PadLeft(25, '-');
        Label1.Text += "<br />";
        Label1.Text += stringValue3.PadLeft(25, '-');
        Label1.Text += "<br />";
        Label1.Text += stringValue4.PadLeft(25, '-');
        Label1.Text += "<br />";
        Label1.Text += stringValue5.PadLeft(25, '-');

        //another technique to format string fixed length
        //String.Format("color = |{0,25}|", stringValue);
    }  
</script>  

<html xmlns="http://www.w3.org/1999/xhtml">  
<head id="Head1" runat="server">  
    <title>c# example - string format fixed length</title>  
</head>  
<body>  
    <form id="form1" runat="server">  
    <div>  
        <h2 style="color:MidnightBlue; font-style:italic;">  
            c# example - string format fixed length
        </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 format fixed length"  
            OnClick="Button1_Click"
            Height="40"  
            Font-Bold="true"  
            />  
    </div>  
    </form>  
</body>  
</html>

c# - How to format a string with leading zeros

Format a String with leading zeros
The String represents text as a sequence of UTF-16 code units. The String is a sequential collection of characters that is used to represent text. The String is a sequential collection of System.Char objects.

The following .net c# tutorial code demonstrates how we can format a String object with leading zeros. In this .net c# tutorial code we will add a specified number of zeros at the beginning of a String instance. The String PadLeft() method allows us to achieve this.

The String PadLeft() method returns a new String of a specified length in which the beginning of the current String is padded with spaces or with a specified Unicode character.

The String PadLeft(int totalWidth, char paddingChar) method overload returns a new String that right-aligns the characters in this instance by padding them on the left with a specified Unicode character for a specified total length.

So we can pass zero ‘0’ for the paddingChar parameter to this method and for totalWidth, we can add the specified number with the String instance length. By doing this, the method returns a String with leading specified numbers of zeros.

The String PadLeft(Int32, Char) overload returns a new String that is equivalent to this instance but right-aligned and padded on the left with as many paddingChar characters as needed to create a length of totalWidth. This method throws ArgumentOutOfRangeException if totalWidth is less than zero.
string-format-leading-zeros.aspx

<%@ Page Language="C#" AutoEventWireup="true"%>

<!DOCTYPE html>  
<script runat="server"> 
    protected void Button1_Click(object sender, System.EventArgs e)  
    {
        //this line create a string variable.
        string stringValue = "asp.net examples";

        //this line create an integer variable.
        int intValue = 12345;

        Label1.Text = "string value: " + stringValue.ToString();
        Label1.Text += "<br />integer value: " + intValue.ToString();

        //string format left padding and right padding
        Label1.Text += "<br /><br />string format left padding with 0: " + stringValue.ToString().PadLeft(stringValue.Length + 1, '0');
        Label1.Text += "<br />string format left padding with 3 zeros: " + stringValue.ToString().PadLeft(stringValue.Length + 3, '0');

        Label1.Text += "<br /><br />string format number to leading 2 zeros: " + intValue.ToString().PadLeft(intValue.ToString().Length + 2, '0');
    }  
</script>  

<html xmlns="http://www.w3.org/1999/xhtml">  
<head id="Head1" runat="server">  
    <title>c# example - string format leading zeros</title>  
</head>  
<body>  
    <form id="form1" runat="server">  
    <div>  
        <h2 style="color:MidnightBlue; font-style:italic;">  
            c# example - string format leading zeros
        </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 format leading zeros"  
            OnClick="Button1_Click"
            Height="40"  
            Font-Bold="true"  
            />  
    </div>  
    </form>  
</body>  
</html>

c# - How to format a string as currency without decimal

String format currency no decimal
the following asp.net c# example code demonstrate us how can we format a string (containing numeric value)to currency with no decimal digit programmatically at run time in an asp.net application. In this example, we format a stringobject containing a decimal number to its equivalent number by rounding it a nearest integer value with dollar currency sign.

A decimal number is a floating-point value that consists of a sign. .Net framework's Decimal.ToString() method convert the numeric valueof this instance to its equivalent string representation. Here we also format the decimal digit using ToString() method.

ToString("C") method format specifier "C" or "c" name is currency. This format specifier return a currency value. We can also use a precisionspecifier to specify number of decimal digit such as ToString("C2"). This ToString("C2") method format a numeric value to its equivalentstring representation with currency sign and two decimal digits. So, if we set the method as ToString("C0") then the method formatthe numeric value with currency sign and without any decimal digit. It round the decimal number to its nearest integer equivalent.
string-format-currency-no-decimal.aspx

<%@ Page Language="C#" AutoEventWireup="true"%>

<!DOCTYPE html>  
<script runat="server"> 
    protected void Button1_Click(object sender, System.EventArgs e)  
    {
        //this line create an int variable.
        int number = 123;

        //this section create decimal variables.
        decimal decimalValue = 421.86M;
        decimal decimalValue2 = 2222.222M;

        //this section create double variables.
        double doubleValue = 741.15;
        double doubleValue2 = 235.47777;
        double doubleValue3 = 235.9;

        Label1.Text = "Integer: " + number;
        Label1.Text += "<br />Decimal: " + decimalValue;
        Label1.Text += "<br />Decimal2: " + decimalValue2;
        Label1.Text += "<br />Double: " + doubleValue;
        Label1.Text += "<br />Double2: " + doubleValue2;
        Label1.Text += "<br />Double3: " + doubleValue3;

        Label1.Text += "<br /><br />formatted string..............";
        //format string using ToString method.
        Label1.Text += "<br />format number to currency no decimal: " + number.ToString("c0");
        Label1.Text += "<br />format decimal value to currency no decimal: " + decimalValue.ToString("c0");
        Label1.Text += "<br />another decimal value to currency no decimal: " + decimalValue2.ToString("c0");
        Label1.Text += "<br />format double to currency no decimal: " + doubleValue.ToString("c0");
        Label1.Text += "<br />another double to currency no decimal: " + doubleValue2.ToString("c0");
        Label1.Text += "<br />another double to currency no decimal: " + doubleValue3.ToString("c0");

        //format string using string.format method.
        Label1.Text += "<br /><br />format decimal value to currency no decimal point: " + string.Format("{0:c0}", decimalValue);
    }  
</script>  

<html xmlns="http://www.w3.org/1999/xhtml">  
<head id="Head1" runat="server">  
    <title>c# example - string format currency no decimal</title>  
</head>  
<body>  
    <form id="form1" runat="server">  
    <div>  
        <h2 style="color:MidnightBlue; font-style:italic;">  
            c# example - string format currency no decimal
        </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 format currency no decimal"  
            OnClick="Button1_Click"
            Height="40"  
            Font-Bold="true"  
            />  
    </div>  
    </form>  
</body>  
</html>