JAVA バッファの検索(\0がはいっていてもOK)

c言語で文字列検索のサンプルはたくさんありますが、バッファの検索がありませんでしたので、下記にまとめます。


バッファといっているのは、文字の途中にNULL文字がある文字列のことです。

このサンプルは文字列の中からキーワードを探し、見つかった場合は
先頭のアドレスを返します。
文字列中に複数キーワードがあれば、検索に失敗するまで繰り返します。

※16進数で進めます

ここからサンプル***************************
#define BUFFER_MAX_RCV 2500
char *c_string = 0x41424300XXXXXXXX;
char *c_key1 = “ABC”;
char *c_key2 = “XYZ”;

while ((c_string = mem_serach(c_string , c_key1 , c_key2 )) != NULL) {

/* メッセージ長の取得 */
i_message_length = 0;
i_message_length = (uc_serch_buf[4] << 8) + uc_serch_buf[5];

/* メッセージ長の分だけバッファをコピー */
memcpy(c_test,uc_serch_buf,i_message_length);

printf(“抽出した文字列\n”);
for (i = 0; i < i_message_length; i++){
printf(“%x “, c_test[i]);
c_test[i] = 0;
}
printf(“\n”);
/* 次のStrString( )の呼び出しに備える */
/* メッセージ長だけポインタを進める */
uc_serch_buf = uc_serch_buf + i_message_length;
i_read_buffer = i_read_buffer + i_message_length;
}

/**
*引数
*uc_s1 検索する文字列
*uc_s2 キーワード1
*uc_s3 キーワード2
**/
unsigned char *mem_serach(const unsigned char *uc_s1, const char *uc_s2, const char *uc_s3)
{
int i_keyword_length;
int i_loop_count;
i_keyword_length = strlen(uc_s2); /* 文字列s2の長さを求める */
for (i_loop_count = 0; i_loop_count < BUFFER_MAX_RCV; i_loop_count++){
if (uc_s1 == 0×00){
/* 検索対象のポインタを一字ずらす */
uc_s1++;
i_read_buffer++;
continue;
}
/* s2の先頭の1文字を探す */
uc_s1 = memchr(uc_s1, uc_s2[0],BUFFER_MAX_RCV – i_read_buffer -i_keyword_length);
if (uc_s1 == NULL) /* 見つからなければ */
return (NULL); /* NULLを返す */
/* 見つかったらn文字比較 */
if(memcmp(uc_s1, uc_s2, i_keyword_length) == 0 || memcmp(uc_s1, uc_s3, i_keyword_length) == 0){
/* 一致したらポインタを返す */
return (unsigned char *)uc_s1;
}
i_read_buffer++;
uc_s1++;
}
return (NULL);
}


Bookmark this on Yahoo Bookmark
Bookmark this on Google Bookmarks
Share on LinkedIn
LINEで送る
Pocket