文字列から特定文字列を検索
ある文字列内に別の文字列が含まれているか確認し、含まれている場合はその先頭が何文字目かを返す。含まれていない場合は -1 が返される。
int match_string(const char * s, const char * x){ // check s includes x or not int base_str_length = strlen(s); int search_str_length = strlen(x); int value = -1; if( base_str_length > search_str_length ){ int i, j; // search string index should be always reset, so j = 0 for( i = 0, j = 0 ; i < base_str_length && value == -1 ; j = 0 ){ if( *(s + i) != *(x + j) ){ i = i + 1; // Check next char continue; } value = i; for( ; j < search_str_length && value != -1 ; j++ ){ if( *(s + i) == *(x + j) ){ i = i + 1; // Check next char continue; } else { // Entering this block means that s includes a part of x, // but not whole same as x. For example, s is aabbcc, x is bbb. // s has bb, this is a part of x, but bb is different from bbb, // not whole same as x. value = -1; // Increment i value shouldn't be done at this block. } } } } return value; }
実行例は以下。
$ ./a.out 01234567890 34 3 $ ./a.out 01234567890 90 9 $ ./a.out 01234567890 2 2 $ ./a.out 01234567890 99 -1 $ ./a.out 01234567890 a -1 $ ./a.out 01234567890 678 6 $ ./a.out 01234567890 45678 4 $ ./a.out 01234567890 00 -1 $ ./a.out 01234567890 01 0 $