-4

c++: can I use .find function to look for multiple characters in a string ex: looking for + and - in an array of linear equations

  • 3
    Not clear. Looking for multiple instances of + or -? Or do you want to know when both exist? Next to each other or separate? Give examples of what should pass and what should fail in your search. – Christopher Pisz Jun 22 '18 at 21:26
  • Don't ask questions that can be answered "yes" or "no". –  Jun 22 '18 at 21:26
  • I want to cut the equation into terms so i want to look for both of them at the same time can i use the .find function or is there another way? – Rania saleh Jun 22 '18 at 21:29
  • 1
    If you want to tokenize it you might be better using `std::regex` and friends. – NathanOliver Jun 22 '18 at 21:32
  • Possible duplicate of [C++: Extracting symbols/variables of an analytical mathematical expression](https://stackoverflow.com/questions/40997788/c-extracting-symbols-variables-of-an-analytical-mathematical-expression) – Jonathan Mee Jun 23 '18 at 00:58

1 Answers1

1

One way of doing it:

auto it = std::find_if( str.begin(), str.end(), [](char c){
    return c == '+' || c == '-';
} );

https://en.cppreference.com/w/cpp/algorithm/find

You could also use std::strpbrk, which searches for one or several separators in a string. https://en.cppreference.com/w/cpp/string/byte/strpbrk

As per your comment you want to tokenize the string, std::strtok will do the job:

char *token = std::strtok( input, "+-" );
while( token != nullptr )
{
    token = std::strtok( NULL, "+-" );
}

https://en.cppreference.com/w/cpp/string/byte/strtok

warning: the above code is not thread safe.

f4.
  • 3,814
  • 1
  • 23
  • 30