【删除公共字符】输入两个字符串,从第一字符串中删除第二个字符串中所有的字符。
例如,输入”They are students.”和”aeiou”,则删除之后的第一个字符串变成”Thy r stdnts.
import java.util.HashMap;
import java.util.Scanner;
public class d2 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String str1 = scan.nextLine();
String str2 = scan.nextLine();
HashMap<Character, Integer> map = new HashMap<>();
//遍历str2
for (int i = 0; i < str2.length(); i++) {
if (map.get(str2.charAt(i)) == null) {
map.put(str2.charAt(i), 1);
} else {
map.put(str2.charAt(i), map.get(str2.charAt(i)) + 1);
}
}
//遍历str1
String ret = "";
for (int i = 0; i < str1.length(); i++) {
if (map.get(str1.charAt(i)) == null){
ret += str1.charAt(i);
}
}
System.out.println(ret);
}
}

该博客介绍了一个简单的Java程序,它接受两个字符串输入,然后从第一个字符串中删除所有出现在第二个字符串中的字符。程序使用HashMap存储第二个字符串中字符的出现次数,随后遍历第一个字符串,仅保留未在HashMap中出现的字符。这是一个基础的字符串操作示例,适用于初级Java程序员学习。
3339

被折叠的 条评论
为什么被折叠?



