HSP教室 入門編
その15 文字列の検索

	;search.as
	;文字列内の該当ワードをサーチする
	;1行内のもの
	;文字列内に複数の該当ワードが存在する場合は、
	;始めのワードにマッチする
	;hct - hit offset (-1 is no hit!)
	tr="The dead dosen't have a call of nature."
	cpw="call"
	;script top
	peek cp,cpw,0	;コンペア用の先頭文字
	hct=-1
	strlen trlen,tr	;ターゲットの長さを図る
	repeat trlen
	if hct!-1:goto *nohit
	 sct=cnt
	 peek code,tr,sct
	 if code!cp :goto *nohit
	 hct=cnt
	 strlen cpwlen,cpw
	 cpct=0
*cplp
	   peek cpt,cpw,cpct
	   peek code,tr,sct
	   if code!cpt :hct=-1:goto *nohit
	   cpct++
	   sct++
	   if cpct<cpwlen:goto *cplp
*nohit
	loop
	mes "0123456789012345678901234567890123456789"
	mes tr
	if hct=-1:mes "no hit"
	mes "hit <"+cpw+"> "+hct
	stop

文字列の検索のサンプルです。
twに検索対象(1行の文)、cpwに検索する文字(検索キーワード)をいれてるとhctに値が入ります。
hitしない場合は−1。
hitした場合はそのオフセットが入ります。
また、1行中に何度かcpwが登場しても、最初のhitしかみていません。
cpwの最初の1文字が無いかをloopしながら探します。
cpwの内容をいろいろ変えて試してみましょう。
数字が並んでいるのは何文字目かという、ものさしがわりに使います。

search.zipをダウンロード。


その16に行く

目次に戻る