我正在编写一个程序,它将打印字符串中的唯一字符(通过扫描仪输入)。我已经创建了一个方法来尝试实现这一点,但我一直在获取不重复的字符,而不是字符串独有的一个或多个字符。我只想要独特的字母。
这是我的代码:
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
原文由 Dextra 发布,翻译遵循 CC BY-SA 4.0 许可协议
根据你想要的输出,你必须替换一个最初已经添加的字符,当它稍后被复制时,所以: