开发者

Find a char or substring with specifying start pos

I couldn't find a function which would let me specify the start pos for beginning a char or substring search.

I have, for example:

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

I'd like search for 'S3' by searching the fi开发者_Python百科rst '*' asterisk and then the second asterisk following it and finally getting the substring 'S3' enclosed by those asterisks.


The string class has a large find family of functions that take an index as a second argument. Repeated applications of find('*', index) should get you what you need.

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);


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


Use

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

See here for reference


#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);
}


You can use strchr(). Simply save the returned pointer and pass it to the next call. As this pointer points to the occurence of your search, the search will start from there.


well one possibility - if you are to use c-style char* arrays for strings - is to use strchr to search for the occurrences of the asterisks, e.g., (and with NO error checking, mind)

 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';
 }

But it would be easier to use the C++ string class to do this.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜