首先让我们看看charAt()使用:
public static void main(String[] args) {
String a = "aabbcc";
for(int i = 0; i < a.length(); i++) {
System.out.print(a.charAt(i) + " ");
}
}
从上述代码可以看出通过charAt(int index)可以获取字符串中的每一个字符,并且每个字符的类型都为char
因此当我们需要一个字符串中的某个字符时,只需输入其下标即可。
LinkedHashSet<String> list = new LinkedHashSet<>();
for(int i = 0; i < str.length(); i++) {
list.add(str.charAt(i) + "");
}
然后让我们创建一个LinkedHashSet对象,并将str字符一个个取出放入对象中,注意:在上方我给LinkedHashSet运用了一个String的泛型,因此需要添加一个空字符将char转为String(不然会报错), 在底层LinkedHashSet有一个可以判断ascii码是否相同的方法,
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
Node<K,V>[] tab; Node<K,V> p; int n, i;
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
else {....
其实到这就差不多就结束了,之后在打印出就行了。
a,b,c的ascii码:
str.value = {byte[6]@703} [97, 97, 98, 98, 99, 99]
this = {Solution@706}
str = "aabbcc"
list = {LinkedHashSet@701} size = 3
0 = "a"
1 = "b"
2 = "c"
如果不想以数组的方式打印出,也可以使用for循环(这里是foreach循环)
for(String s : list) {
System.out.print(s);
}