我正在尝试打印字符串中的所有唯一字符,但没有得到正确的输出。另外,我想检查是否有人在字符串中输入整数,我想打印无效字符串。我怎样才能实现这个目标?
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
char[] ch = new char[20];
System.out.println("Enter the sentence:");
String sent = sc.nextLine().replaceAll(" ", "");
int count = 0;
for (int i = 0; i < sent.length(); i++) {
int j = (sent.length() - 1);
count = 0;
while (j > i) {
if (sent.charAt(j) == sent.charAt(i)) {
sent = deleteCharAt(sent, i);
sent = deleteCharAt(sent, j - 1);
break;
}
j--;
}
}
for (int i = 0; i < sent.length(); i++) {
System.out.println(sent.charAt(i));
}
}
private static String deleteCharAt(String strValue, int index) {
return strValue.substring(0, index) + strValue.substring(index + 1);
}
Enter the sentence:
java is good object oriented programming language
a
v
i
s
o
d
b
c
r
e
e
d
p
g
m
m
n
l
u
最佳答案
您可能想要使用Set
。这些数据结构类似于 List
,除了:
- 它们没有顺序(这意味着您无法调用
set.get(3)
) - 他们不允许重复
您可以将它们视为没有任何值的Map
。
如果您有一个String
并且您想从中获取所有唯一的char
。步骤如下:
String string = "hello"; // 4 unique characters
Set<Character> uniqueChars = new HashSet<>(); // create an empty set to put the unique chars into
// split into char[]
char[] chars = string.toCharArray();
Arrays.stream(chars).forEach(c -> {
// the following code will be run once for every char in the array
uniqueChars.add(c);
// adding the same char twice does not insert it twice
});
这可以更简洁地写为:
String string = "hello";
Set<Character> uniqueChars = new HashSet<>();
Arrays.stream(string.toCharArray()).forEach(uniqueChars::add); // using a Java 8 method reference
如果您想拒绝任何数字char
,您可以使用以下行:
boolean containsDigit = Arrays.stream(string.toCharArray())
.filter(Character::isDigit) // filter out all the non digit characters
.findAny() // check if there are any remaining
.isPresent();
关于java - 字符串中的唯一字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59916553/