Java字符串参数介数组应用&忽略空格字符串相等判断"以字符串相同实验为例"

Q16. Write a method named areAnagrams that accepts two Strings as parameters and returns whether those strings contain the same letters (in any order).
areAnagrams(“bear”, “bare”) returns true
areAnagrams(“sale”, “sail”) returns false
Q16.
此实验要求,以两个字符串为参数输出是否包含一样的字符。此方法更进一步给出了忽略空格字符“ ”判断的方法
并以博主印象最深的伏地魔的名字作为实验样本

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;
	}
}

你可能感兴趣的:(Java)