How to use substr but use variable in c++

I want to fetch code between "is " & " ok" text using substr from string str
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
    #include <iostream>
    #include <string>
    
        int main ()
        {
          std::string str="Your random code is A23MZ1 ok ?";
          
          std::size_t pos = str.find("is ");
          std::size_t pos2 = str.find(" ok");
        
          std::string str3 = str.substr (pos,pos2);
        
          std::cout << str3 << '\n';
        
        }

Output code above : is A23MZ1 ok ?
The output I expected : A23MZ1
Change pos2 to pos2-pos in the substring argument. The substr() method works by number of characters, not by slicing as in many other languages.

But I think you need to consider carefully what happens if one of those target strings is not found.
The second parameter of substr takes the length.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
 #include <iostream>
    #include <string>
    
    int main ()
    {
      std::string str="Your random code is A23MZ1 ok ?";
      
      std::size_t pos = str.find("is ");
      std::cout << "pos of 'is ': " << pos << "\n";
      std::size_t pos2 = str.find(" ok");
      std::cout << "pos of 'ok ':" << pos2 << "\n";
    
      std::string str3 = str.substr (pos+3,pos2-pos-3);
    
      std::cout << str3 << '\n';
    
    }
You should start the search for ok after the position of is in case ok comes before is in the string:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
#include <string>

int main()
{
	const std::string str {"Your random code is A23MZ1 ok ?"};

	if (const auto pos1 {str.find("is ")}; pos1 != std::string::npos) {
		const auto pos2 {str.find(" ok", pos1)};
		const std::string str3 {str.substr(pos1 + 3, pos2 != std::string::npos ? pos2 - pos1 - 3 : pos2)};

		std::cout << str3 << '\n';
	}
}

Topic archived. No new replies allowed.