文字列の検索
●char型,boolean型
char型には2バイトのUNICODE文字('あ'、'a'など)を、
boolean型には真偽値(trueまたはfalse)を格納します。
char 変数名 = '初期値';
booolean 変数名 = 初期値;
●charAt
charAt(n)はn番目の文字を返します。
●サンプル
import java.io.*;
public class NewMain {
public static void main(String[] args) throws IOException {
String str, s;
int p, pos=0, cnt=0;
BufferedReader= new BufferedReader(new InputStreamReader(System.in));
System.out.print("文字列を入力してください > ");
str = br.readLine(); //文字列の入力
System.out.print("検索する文字(列)を入力してください > ");
s = br.readLine(); //検索文字の入力
System.out.println("検索結果:");
while((p=str.indexOf(s,pos)) != -1) {
System.out.println("位置 " + p);
cnt++;
pos = p+1;
}
if(cnt > 0) {
System.out.println("以上の位置で見つかりました。");
}else {
System.out.println("見つかりませんでした。");
}
}
}
●実行結果
文字列を入力してください > abcacbabc
検索する文字(列)を入力してください > c
検索結果:
位置 2
位置 4
位置 8
以上の位置で見つかりました。