ViVi Home > 技術文書 > ポインタ入門 > 文字列関数 > ends_with


 

 

C/C++ ポインタ入門 > 文字列関数 > ends_with
Nobuhide Tsuda
Nov-2013

文字列の末尾パターン照合:bool my_ends_with(const char *text, const char *pat)

bool my_ends_with(const char *text, const char *pat)
{
   
int plen = strlen(pat);
   
if( plen == 0 ) {
       
return true;     // パターンが空文字列の場合は、常に true を返す
   
}
   
int tlen = strlen(text);
   
if( plen > tlen ) {
       
return false;     // パターン長がテキスト長より大きい場合は、常に false を返す
   
}
    text
+= tlen - plen;     // text を末尾のパターン位置に合わせる
   
while( *text == *pat ) {      // text, pat の指す先が等しい間ループ
       
if( *text == '\0' ) {
           
return true;         // 終端まで一致した場合は true を返す
       
}
       
++text;       // ポインタを先に進める
       
++pat;
   
}
   
return false;     // 不一致があった場合は false を返す
}

解説:

 


前: | 次: