Javaの文字列操作
例えば、"aaaa-bbbbb-ccccccc-ddddddd"という文字列があり("-"を仕切として)左から数えて3ブロック目だけを取り出すためにはどうすればいいだろうか。
String code = "aaaa-bbbbb-ccccccc-dddddd";
String MARK = "-";
int DST_BEGIN = 0;
//start
int start = code.indexOf(MARK, code.indexOf(MARK)+1);
//end
int end =code.indexOf(MARK,start+1);
//記憶領域
char[] dst = new char[end-start-1];
//コピー
code.getChars(start+1,end,dst,DST_BEGIN);
//char→string
String new_code = new String(dst);
では無限にこの規則が続いてたとしてN番目のブロックを取り出すにはどうしたいいだろうか。(aaaa-bbbbb-ccccc-ddddd-・・・・・-abababa-・・・・)
ブロック数をNUMとして文字列を返すメソッドを書くと、
String pickUpStr(String code,String MARK,int NUM){
int DST_BEGIN = 0;
int start=0;
//start
while(1では有限にこの規則が続いていたとしてN番目のブロックを取り出すにはどうしたいいだろうか。(最後は"-"以外で終わる)
NUMには0以上を入れるとするとメソッドは,
となる。
String pickUpStr(String code,String MARK,int NUM){
int DST_BEGIN = 0;
int start=0;
int end =0;
//last index
int last = code.lastIndexOf(MARK);
//start index
while(1= last) break;
start =code.indexOf(MARK, start+1);
}
//end index
if(start >= last) end = code.length();
else end =code.indexOf(MARK,start+1);
//記憶領域
char[] dst = new char[end-start-1];
//コピー
code.getChars(start+1,end,dst,DST_BEGIN);
//char→string
String new_code = new String(dst);
return new_code;
}