Java文字列パラメータ誘電配列適用&スペース文字列等を無視判断「文字列同一実験を例に」

13017 ワード

Q 16.Write a method named areAnagrams that accepts two Strings as parameters and returns whether those strings contain the same letters.areAnagrams(「bear」,「bare」)returns true areAnagrams(「sale」,「sail」)returns false Q 16.この実験要求は、2つの文字列をパラメータとして同じ文字が含まれているか否かを出力する.この方法はさらに,スペース文字「」の判断を無視する方法を示し,ブロガーの印象が最も深い伏地魔の名前を実験サンプルとした.
import java.util.*;
import java.util.Scanner;
public class Q16 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner console =new Scanner (System.in);
		
		/*System.out.println("Type your first string");
		String first = console.next();
		System.out.println("Type your second string");
		String second = console.next();*/
		//    ,            
		String first = "TOM MARVOLO RIDDLE";
		String second = "I AM LORD VOLDEMORT";
		char [] name1distri = first.toCharArray();
		char [] name2distri = second.toCharArray();
		Arrays.sort(name1distri);
		Arrays.sort(name2distri);
/*           
[ ,  , A, D, D, E, I, L, L, M, M, O, O, O, R, R, T, V]
[ ,  ,  , A, D, D, E, I, L, L, M, M, O, O, O, R, R, T, V]     ,            ,          “ ” */
		boolean result =areAnagrams(name1distri,name2distri); 
		System.out.println(Arrays.toString(name1distri));
		System.out.println(Arrays.toString(name2distri));
		System.out.println(result);
	}
	public static boolean areAnagrams(char[]num1,char[]num2) {
	//                  boolean  
		boolean result = false;
		int count =0;
		//         
		int nonezero = 0;
		//        
		for (int i=0;i<num1.length;i++) {
			if (num1[i]!=' ') {
				count++;
			}else {
				nonezero++;
			}
		}
		int [] num1Nospace = new int [count];
		//    char [] num1Nospace = new char [count]
		for (int b=0;b<count;b++) {
			num1Nospace[b] = num1[nonezero+b];
			}
		count =0;
		nonezero =0;
		//     0,0;
		for (int a=0;a<num2.length;a++) {
			if (num2[a]!=' ') {
				count++;
			}else {
				nonezero++;
			}
		}
		int [] num2Nospace = new int [count];
		//    char [] num2Nospace = new char [count]
		for (int c=0;c<count;c++) {
			num2Nospace[c] = num2[nonezero+c];
			}
		count =0;
		nonezero =0;
		if (Arrays.equals(num1Nospace, num2Nospace)) {
			result =true;
		}
		/*System.out.println(Arrays.toString(num1Nospace));
		System.out.println(Arrays.toString(num2Nospace));*/
		/*     ,   chart *     ,
		[65, 68, 68, 69, 73, 76, 76, 77, 77, 79, 79, 79, 82, 82, 84, 86]
[65, 68, 68, 69, 73, 76, 76, 77, 77, 79, 79, 79, 82, 82, 84, 86]
     chart        chart  ,  
[A, D, D, E, I, L, L, M, M, O, O, O, R, R, T, V]
[A, D, D, E, I, L, L, M, M, O, O, O, R, R, T, V] */
		return result;
	}
}