Find a char or substring indicating the beginning of pos

I could not find a function that would allow me to specify the beginning of pos to start searching for a char or substring.

I have for example:

char *c = "S1S2*S3*S4";

I would like to find the " S3" by searching the first asterisk " *", then the next second asterisk, and finally getting the substring " S3" enclosed by these asterisks.

+3
source share
6 answers

One solution would be to find the location of the first star and then the location of the second star. Then use these positions as your start and end locations for your search S3.

+2
source

string find, . find('*', index) , .

std::string s(c);
std::string::size_type star1 = s.find('*');
std::string::size_type star2 = s.find('*', star1 + 1);
std::string last_part = s.substr(star2 + 1);
+9

char *strchr( const char *str, int ch );

+1
#include <string>

std::string between_asterisks( const std::string& s ) {
    std::string::size_type ast1 = s.find('*');
    if (ast1 == std::string::npos) {
        throw some_exception();
    }
    std::string::size_type sub_start = ast1+1;
    std::string::size_type ast2 = s.find('*', sub_start);
    if (ast2 == std::string::npos) {
        throw some_exception();
    }
    return s.substr(sub_start, ast2-sub_start);
}
0

strchr(). . , .

0

- c-style char * - strchr , , ( , )

 char c []= "S1S2*S3*S4";

 char* first = strchr(c,'*');
 if (first) {
   char* start = ++first;
   char* nextast = strchr(start,'*');
   char* s3str = new char[nextast-start+1];
   strncpy(s3str,start,nextast-start);
   s3str[next-start] = '\0';
 }

++.

0

Source: https://habr.com/ru/post/1776714/


All Articles