none
How to check whether a character is present in the string or not RRS feed

All replies

  • Suppose string is  "+123" or "-345"

    need to check + is present or not using C#

    https://www.dotnetperls.com/indexof
    Tuesday, June 4, 2019 5:21 AM
  • Hi abcdefgefdedfd,

    Thank you for posting here.

    Based on your description, you want to check if a charater is in the string or not.

    You could try the following code.

     string m = "+123";
                if(m.Contains('+'))
                {
                    Console.WriteLine("char {0} exists in the string {1}","+",m);
                }
                else
                {
                    Console.WriteLine("char {0} does not in the string {1}", "+", m);
                }

    Result:

    Best Regards,

    Jack


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    • Proposed as answer by ME_77 Thursday, June 6, 2019 7:59 AM
    Tuesday, June 4, 2019 5:38 AM
    Moderator
  • Also, check this:

     

       bool is_plus = mystring.StartsWith("+");

    Tuesday, June 4, 2019 5:45 AM
  • Trimming the string before using StrartsWith might also be useful, in case there's a leading space.

             string s = " +123";
             bool isPlus = s.Trim().StartsWith("+"); // = true

    Tuesday, June 4, 2019 6:07 AM
  • Contains is better

    Tuesday, June 4, 2019 6:33 AM
  • A slick option where you can ignore the + :

    using System;
    using static System.Console;
    namespace ConsoleApp1
    {
        class Program
        {
            static void Main(string[] args)
            {
                string s = "7";
                int i = int.Parse(s);
                if(i>=0) WriteLine("Number is positive");
            }
        }
    }




    • Edited by ThisNewbie Tuesday, June 4, 2019 8:11 AM
    Tuesday, June 4, 2019 8:02 AM
  • Hi

    Is your problem solved? If so, please post "Mark as answer" to the appropriate answer, so that it will help other members to find the solution quickly if they face a similar issue.

    Best Regards,

    Jack


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Thursday, June 6, 2019 6:49 AM
    Moderator