A-B
描述
本题要求你计算A−B。不过麻烦的是,A和B都是字符串 —— 即从字符串A中把字符串B所包含的字符全删掉,剩下的字符组成的就是字符串A−B。
输入
输入在2行中先后给出字符串A和B。两字符串的长度都不超过104,并且保证每个字符串都是由可见的ASCII码和空白字符组成,最后以换行符结束。
输出
在一行中打印出A−B的结果字符串。
首先输入语句一定要有(作为学java的一员,一定都会吧),那么这道题的重点就是解决吧相同字母删除的问题了。怎么将字符串中的元素一一分开呢?我们考虑使用charAt(根据题中ASCll也可以想到charAt哦)。我们来看看charAt的源代码:
public char charAt(int index) {
if (isLatin1()) {
return StringLatin1.charAt(value, index);
} else {
return StringUTF16.charAt(value, index);
}
}
/**
* Returns the character (Unicode code point) at the specified
* index. The index refers to {@code char} values
* (Unicode code units) and ranges from {@code 0} to
* {@link #length()}{@code - 1}.
*
* <p> If the {@code char} value specified at the given index
* is in the high-surrogate range, the following index is less
* than the length of this {@code String}, and the
* {@code char} value at the following index is in the
* low-surrogate range, then the supplementary code point
* corresponding to this surrogate pair is returned. Otherwise,
* the {@code char} value at the given index is returned.
*
* @param index the index to the {@code char} values
* @return the code point value of the character at the
* {@code index}
* @exception IndexOutOfBoundsException if the {@code index}
* argument is negative or not less than the length of this
* string.
* @since 1.5
*/
注释部分翻译过来就是:
利用这一特性,我们就可以完成我们的程序,解决此问题啦。在确定字符变量的时候,可以把B的字符统一赋值为相同的整型变量哦,如果A中含有相同的变量就不输出,直达A、B不一样为止,输出。
接下来就是代码展示啦,这个代码我也是从大佬那里学来的哦。
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String A= sc.nextLine();
String B= sc.nextLine();
int[] a = new int[1000];
for (int i = 0; i < B.length(); i++) {
a[B.charAt(i)] = 1;
}
for (int i = 0; i < A.length(); i++) {
if (a[A.charAt(i)] != 1) {
System.out.print(A.charAt(i));
}
}
}
}