Home > Enterprise >  How can I find object in array in a string?
How can I find object in array in a string?

Time:04-09

So I have an array that looks as such:

std::string Operators[4] = {
  " ",
  "-",
  "*",
  "/"
};

And I have another string, that looks like this

std::string Equation = "1 1";

I'm trying to make the code check if the plus from the array is in the equation string. Is it no different than finding a substring in a string? Any help is greatly appreciated.

CodePudding user response:

Go through the member functions of std::string class and specifically, for your purpose, check the Search member functions.

Below is an example of using find member function of std::string class for finding Operators in Equation:

#include <string>
#include <iostream>
 
int main()
{
    std::string Operators[4] = {
      " ",
      "-",
      "*",
      "/"
    };
    
    std::string Equation = "1 1";
 
    for (std::size_t i = 0; i < sizeof(Operators)/sizeof(Operators[0]);   i) {
        std::string::size_type n = Equation.find(Operators[i]);

        std::cout << Operators[i] << " : ";
        if (n == std::string::npos) {
            std::cout << "not found\n";
        } else {
            std::cout << "found at position : " << n << '\n';
        }
    }

    return 0; 
}

Output:

# ./a.out
  : found at position : 1
- : not found
* : not found
/ : not found

Note that, in the above program, if you change the type of Operators array to

char Operators[4] = {
  ' ',
  '-',
  '*',
  '/'
};

it will work absolutely fine without any other change because the find member function has an overload which takes char as argument.

CodePudding user response:

From what I can see, it does not seem different. Maybe the issue was what the commenter said, changing your array of strings to an array of chars. Regardless this code works for your scenario:

int main() {

  std::string str = "1 1";
  
  char Operators[4] = {' ','-','*','/'}; // using the commenters suggestion, char array is better

  for (int i = 0; i < 4; i  ) {
    for (int j = 0; j < str.length(); j  ) {
      if (Operators[i] == str[j])
        std::cout << "A '" << Operators[i] << "' is present" << std::endl;
    }
  }

  return 0;

}

As another commenter said, you could also use an iterator.

CodePudding user response:

use find_first_of

 std::string Equation = "1 1";

 std::size_t found = Equation.find_first_of(" -/*");

if char is found 'found' will be the offset (1 in this case). If not found then 'found' will equal std::string::npos

See

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

To know which operator was found do

   char op = Equation[found];
  • Related