我想找到由a到z的随机字母组成的大二维数组中的字母组合。 字母的组合首先如下:字母' a',第二个字母直接在这个字母之后' l'之后的第三个字母将再次成为' a'。 如果找到这些字母的组合,那么我想将它出现的数量增加1.所以最后我会确切地知道这些特定字母按此顺序彼此相邻地随机生成的次数。
char[][] x = new char[1000][1100];
int amountofAla = 0;
for (int i=0; i<x.length; i++) {
for (int r=0; r<x[i].length; r++) {
x[i][r] = abc.charAt((int)(Math.random()*26)) ;
}
} // my 2d tab with random generated letters was made here
// below is my attempt to find combination of letters 'a'+'l'+'a'
for (int i=0; i<x.length; i++)
{
for (int w=0; w<x.length; w++)
{
if (x[i][w] ==('a') && x[i][w+1] == 'l' && x[i][w+2] == 'a')
amountofAla = amountofAla+1 ;
else;
}
}
System.out.println("occurance= " + amountofAla);
我按此顺序查找信件的尝试是错误的数字。我打印了标签并搜索了ala manualy,数字总是错误的。
// print array for refference
for (int i=0; i<x.length; i++) {
for (int r=0; r<x[i].length; r++) {
System.out.print( x [i] [r]);
} System.out.println( );
}
提前感谢您对特定问题的任何想法。
答案 0 :(得分:0)
如果转换&#34;行&#34;你的2d数组从char []到string然后你不需要自己处理匹配。有两种方法可以找出&#34; ala&#34;:
的出现次数首先使用正则表达式
public static void main (String []args){
char[][] x = new char[10][11];
int amountofAlaTotal = 0;
String abc = "abcdefghijklmnopqrstuvwxyz";
for (int i=0; i<x.length; i++) {
for (int r=0; r<x[i].length; r++) {
x[i][r] = abc.charAt((int)(Math.random()*26)) ;
}
}
for (int i=0; i<x.length; i++) {
String str = String.valueOf(x[i]); //convert a char array to a string
Pattern p = Pattern.compile("ala");
Matcher m = p.matcher(str);
int amountofAlaPerLine = 0;
while (m.find()){
amountofAlaPerLine +=1;
}
if(amountofAlaPerLine>0){
System.out.println("str: "+str );
System.out.println("index: " + i );
System.out.println("matches: "+amountofAlaPerLine);
}
amountofAlaTotal += amountofAlaPerLine;
}
System.out.println("total: "+amountofAlaTotal );
}
或第二次使用来自Apache Commons Lang的StringUtils.countMatches
public static void main (String []args){
char[][] x = new char[10][11];
int amountofAlaPerLine = 0;
int amountofAlaTotal = 0;
String abc = "abcdefghijklmnopqrstuvwxyz";
for (int i=0; i<x.length; i++) {
for (int r=0; r<x[i].length; r++) {
x[i][r] = abc.charAt((int)(Math.random()*26)) ;
}
}
for (int i=0; i<x.length; i++) {
String str = String.valueOf(x[i]); //convert a char array to a string
amountofAlaPerLine = StringUtils.countMatches(str, "ala"); //count matches
if(amountofAlaPerLine>0){
System.out.println("str: "+str );
System.out.println("index: " + i );
System.out.println("matches: "+amountofAlaPerLine);
}
amountofAlaTotal += amountofAlaPerLine;
}
System.out.println("total: "+amountofAlaTotal );
}