我正在编写一个程序来打印字符串中的唯一字符(通过扫描仪输入)。我已经创建了一个方法来尝试实现这一点,但我一直在获取不重复的字符,而不是字符串独有的一个或多个字符。我只想要独特的字母。
这是我的代码:
import java.util.Scanner;
public class Sameness{
public static void main (String[]args){
Scanner kb = new Scanner (System.in);
String word = "";
System.out.println("Enter a word: ");
word = kb.nextLine();
uniqueCharacters(word);
}
public static void uniqueCharacters(String test){
String temp = "";
for (int i = 0; i < test.length(); i++){
if (temp.indexOf(test.charAt(i)) == - 1){
temp = temp + test.charAt(i);
}
}
System.out.println(temp + " ");
}
}
下面是上面代码的示例输出:
Enter a word:
nreena
nrea
预期输出为:ra
最佳答案
根据你想要的输出,你必须替换一个最初已经添加的字符,当它后来有重复时,所以:
public static void uniqueCharacters(String test){
String temp = "";
for (int i = 0; i < test.length(); i++){
char current = test.charAt(i);
if (temp.indexOf(current) < 0){
temp = temp + current;
} else {
temp = temp.replace(String.valueOf(current), "");
}
}
System.out.println(temp + " ");
}
关于Java:打印字符串中的唯一字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40899915/