所以我在这里基本上要做的是从数组中取出'S''P''O''R''T'等字符,其中包含来自'A'的所有字母... 'Z'这段代码工作正常,但我想知道是否有更好的方法来做...更简化的版本左右..我会很感激答案,只涉及数组n不列表或哈希!
String key = "SPORT";
char [] keys = key.toCharArray();
String alphabets = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
char [] alpha = alphabets.toCharArray();
int len = alpha.length;
int keylen = keys.length;
System.out.println(len);
int new_len = (alpha.length) - keylen;
char [] newalpha = new char [new_len];
for (int j = 0 ; j < keys.length ; j++) {
for (int i = 0 ; i < len ; i++) {
if (alpha[i] == keys[j]) {
alpha[i] = '@';
}
}
}
int k = 0;
for (int i = 0 ; i < len ; i++) {
if (alpha[i] != '@') {
newalpha[k] = alpha[i];
k++;
}
}
for (int i = 0 ; i < newalpha.length ; i++) {
System.out.println(newalpha[i]);
}
答案 0 :(得分:1)
在Java 8中
<强>代码强>:
String alphabets = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
List<String> list = Arrays.asList(alphabets.split(""));
List<String> result = list.stream().filter(s -> !(s.equals("S") || s.equals("P") || s.equals("O")
|| s.equals("R") || s.equals("T"))).collect(Collectors.toList());
System.out.println("The list of letters after after extractison S P O R T are ");
result.stream().forEach(s -> System.out.print(" " + s));
System.out.println("");
System.out.println("The number of letters after extractison S P O R T is " + result.stream().count());
<强>输出强>:
The list of letters after after extractison S P O R T are
A B C D E F G H I J K L M N Q U V W X Y Z
The number of letters after extractison S P O R T is 21
解释:
据我所知,Java 8
中的lambda只适用于List,所以我使用Arrays.asList
将String转换为列表。接下来,我使用filter
作为if
语句来查看列表并忽略S P O R
和T
并将其收集为List
命名结果。最后,我使用for loop
的新形式打印列表,并显示提取这些字母后我们有多少个字母。
清理版本:
import java.util.*;
import java.util.function.Predicate;
import java.util.stream.Collectors;
public class TakeOutChars {
public static void main(String[] args) {
String alphabets = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
List<String> list = Arrays.asList(alphabets.split(""));
System.out.println(filterSPORT(list, ignoreSPORT()));
System.out.println(filterSPORT(list, ignoreSPORT()).stream().count());
}
public static Predicate ignoreSPORT() {
return s -> !(s.equals("S") || s.equals("P") || s.equals("O")
|| s.equals("R") || s.equals("T"));
}
public static List<String> filterSPORT(List list, Predicate predicate) {
return (List<String>) list.stream().filter( predicate ).collect(Collectors.toList());
}
}
清理版本的输出:
[A, B, C, D, E, F, G, H, I, J, K, L, M, N, Q, U, V, W, X, Y, Z]
21
答案 1 :(得分:0)
您可以使用以下提到的代码:
String key = "SPORT";
key = key.toUpperCase();
char[] keys = key.toCharArray();
String alphabets = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
for (char c : keys) {
alphabets = alphabets.replace(c, '@');
}
alphabets = alphabets.replaceAll("@", "");
System.out.println(alphabets);