Check whether a character is present in String (Text) using C# .Net

Last Reply on Aug 07, 2015 10:09 AM By dharmendr

Posted on Aug 07, 2015 07:50 AM

Input is taken from keyboard

ex:"siva" input

Output is 

If we press 's' outpout is only   s

If we press 'v' outpout is only   siv

If we press 'a' outpout is only   siva

If we press 'i' outpout is only   si

if we press other then this characters it gives error.

Posted on Aug 07, 2015 10:09 AM Modified on on Aug 28, 2017 05:34 AM

Hi Anand,

I have made a sample that full-fill your requirement.

HTML

<div>
    Enter Value :
    <asp:TextBox ID="txtValue" runat="server" />
    <br />
    Enter Key:
    <asp:TextBox ID="txtKeyWord" runat="server" />
    <br />
    <asp:Button ID="btnCheck" Text="Check" runat="server" OnClick="CheckKeyAvailability" />
    <br />
    <asp:Label ID="lblResult" runat="server" Visible="false" />
</div>

Code

protected void CheckKeyAvailability(object sender, EventArgs e)
{
    string value = txtValue.Text.Trim();
    string key = txtKeyWord.Text.Trim();
    string result = string.Empty;
    int index = value.LastIndexOf(key);
    if (index != -1)
    {
        result = value.Substring(0, index + key.Length);
    }
    if (!string.IsNullOrEmpty(result))
    {
        lblResult.Text = result;
    }
    else
    {
        lblResult.Text = "Key not found";
    }
    lblResult.Visible = true;
}

Screenshot

Hope this will help you.