題目:
有兩個字符串由不同的字母組成店印,一長一短倒慧,長的為A短的為B按摘。設(shè)計一個算法纫谅,如果所有在B中出現(xiàn)的字符都在A中出現(xiàn),則返回true付秕,否則返回false。
使用indexOf()和charAt()兩種方法進行判斷:
package com.company;
import java.util.Scanner;
/**
* 判斷一個字符串的所有字母是否包含在另一個字符串中
*/
public class Test {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("請輸入兩個字符串:");
Scanner sc = new Scanner(System.in);
String i = sc.nextLine();
String j = sc.nextLine();
// System.out.println("字符串比較結(jié)果為:"+checkFun(i, j));
System.out.println("字符串比較結(jié)果為:" + checkFun1(i, j));
}
// 方法1 indexOf
private static boolean checkFun(String i, String j) {
String a;
String b;
if (i.length() > j.length()) {
a = i;
b = j;
} else {
a = j;
b = i;
}
int count = 0;
for (int bi = 0; bi < b.length(); bi++) {
String[] bArr = b.split("");
if (a.indexOf(bArr[bi]) != -1) {
count++;
} else {
break;
}
}
if (b.length() == count) {
return true;
} else {
return false;
}
}
// 方法2 charAt
private static boolean checkFun1(String i, String j) {
String a;
String b;
if (i.length() > j.length()) {
a = i;
b = j;
} else {
a = j;
b = i;
}
int count = 0;
for (int bj = 0; bj < b.length(); bj++) {
for (int ai = 0; ai < a.length(); ai++) {
if (a.charAt(ai) == b.charAt(bj)) {
count++;
break;
}
}
}
if (count == b.length()) {
return true;
} else {
return false;
}
}
}
運行結(jié)果:
請輸入兩個字符串:
sdjfksbsdssbds
swednd
字符串比較結(jié)果為:false
請輸入兩個字符串:
qwert
weee
字符串比較結(jié)果為:true
其中方法二中兩層for循環(huán)遍歷的時候記得拿短的字符串去與長的字符串進行比較,即第一層for循環(huán)為短的字符串汰寓。
原文作者技術(shù)博客:http://www.reibang.com/u/ac4daaeecdfe