Link to home
Start Free TrialLog in
Avatar of Skale
Skale

asked on

Check string contains mathematical symbols inside it in C#

Hello i'd like to crate a function which will check string and if it's contains any of +.-.*./ ,^ these i'd like to get a boolean false from that function.

Is there anyway to do that simply or i had to create switch operator for each one?

Any help would be grateful.

Thank you.
Avatar of Dr. Klahn
Dr. Klahn

There's a standard function for this, find_first_of.

http://www.cplusplus.com/reference/string/string/find_first_of/

"Find character in string
Searches the string for the first character that matches any of the characters specified in its arguments."
SOLUTION
Avatar of Rikin Shah
Rikin Shah
Flag of India image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Go with Rikin's answer.  Index of will give you. Number for the position (0 based) of a single character.  IndexOfAny will take a character array and will return the first position it finds.  If nothing is found by either of these methods the return value is -1.  Since the string is treated as an array all positions will be 0 based if that is at all useful for you to further develop this bit of code.
If the method returns -1 you can return False else True.
the original post requires to return True if  no math operator could be found (see also sample output it_saige has posted).

beside of that i support Rikin's solution using String.IndexOfAny which exactly does what was asked for.

public static bool HasNoMathOps(String str)
{
      char [] mathops = { '+', '-', '*', '/', '^' };
      return (str.IndexOfAny(mathops) < 0); 
}

Open in new window


however, returning a bool (only) gives away the additional information IndexOfAny could provide. for example if you want to parse an expression which might contain operators or even if you want to program a calculator.

enum MathOp { noop = -1, plus, minus, times, divided, power };
public static MathOp FindNextMathOp(String str, ref int pos)
{
      char [] mathops = { '+', '-', '*', '/', '^' };
      // start at position given by pos
      pos = str.IndexOfAny(mathops, pos);
       if (pos >= 0) 
       {
              return (MathOp)Array.IndexOf(mathops, str[pos]);
       }
       return noop; 
}

Open in new window


you could use the function like

   string s = "1 + (5 - 7) * 2 + (2^x))";  
   int pos = 0;
   MathOp op = noop;
   while ((op = FindNextMathOp(s, pos)) != noop)
   {
          Console.WriteLine("Operator {0} found at position {1}\n", op.ToString(), pos):
          pos++;
   }

Open in new window


(code not tested).

Sara
Hi Hakan,

i would suggest using the regular expression because it gives you flexibility and not limit you to fixed set of characters if you want to go this approach. Please see the below code and change it as per your requirement. Also if you want to know more about regular expression in C# and how you can leverage the power of RegEx please go through this article: System.Text.RegularExpressions Namespace

using System;
using System.Text.RegularExpressions;


public class Program
{
  public static void Main()
  {
    string text = "Find symbol +$-/# in this string";
    string pat = @"\W";

    // Instantiate the regular expression object.
    Regex r = new Regex(pat, RegexOptions.IgnoreCase);
    
    // Match the regular expression pattern against a text string or symbol.
    Match m = r.Match(text);

    if(m.Success)
    {
      Console.WriteLine("Match found for symbol!!!");
    }
  }  
}

Open in new window

Output:
User generated image
regular expressions have a few disadvantages: the syntax is rather complex and you need much time and patience before you safely could use them. then, beside of trivial cases there is no proof that an expression that is valid for a set of sample strings would give a valid match for all strings. any change of the expressions requires to repeat all tests made before to make sure that the change wouldn't affect the match results so far. finally, for a rather simple problem to check whether an expression contaiins some math characters, the regex functions are pure overkill regarding both the efforts to define the expression and the costs of execution.

the function String.IndexOfAny suggested by Rikin is the right way to go.

Sara