Home c++ Finding the position of a character in a string

Finding the position of a character in a string

Author

Date

Category

There is a line, in it you need to find the symbol '=' and write its position to a variable. What solutions are there?


Answer 1, authority 100%

To find an element in a string, use the std :: string: find , it will return the position of the first occurrence. If the character or substring is not in the original string, it will return std :: string: : npos :

std :: string equation = "1 + 2 = 4";
std :: cout & lt; & lt; equation.find ('=') & lt; & lt; std :: endl;

Answer 2, authority 100%

You did not say what type of object you have the string in.

Below is a demo program that searches for a character in the character array s1 and in an object named s2 of the class std :: string .

# include & lt; iostream & gt;
#include & lt; string & gt;
#include & lt; cstring & gt;
int main ()
{
  char s1 [] = "2 * 2 = 4";
  std :: string s2 (s1);
  char c = '=';
  char * p = std :: strchr (s1, c);
  if (p! = nullptr)
  {
    std :: cout & lt; & lt; "Character" & lt; & lt; c & lt; & lt; "found at position" & lt; & lt; p - s1 & lt; & lt; std :: endl;
    std :: cout & lt; & lt; "The rest of the string is \" "& lt; & lt; p & lt; & lt;" \ "" & lt; & lt; std :: endl;
  }
  std :: string :: size_type n = s2.find (c);
  if (n! = std :: string :: npos)
  {
    std :: cout & lt; & lt; "Character" & lt; & lt; c & lt; & lt; "found at position" & lt; & lt; n & lt; & lt; std :: endl;
std :: cout & lt; & lt; "The rest of the string is \" "& lt; & lt; s2.substr (n) & lt; & lt;" \ "" & lt; & lt; std :: endl;
  }
}

The program output to the console looks like this:

Character '=' found at position 6
The rest of the string is "= 4"
Character '=' found at position 6
The rest of the string is "= 4"

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions