Java:打印字符串中的唯一字符

标签 java string character unique

我正在编写一个程序来打印字符串中的唯一字符(通过扫描仪输入)。我已经创建了一个方法来尝试实现这一点,但我一直在获取不重复的字符,而不是字符串独有的一个或多个字符。我只想要独特的字母。

这是我的代码:

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/

相关文章:

java - ExecutorService 执行 REST 请求

java - JPA @ElementCollection @Enumerated 不插入

C++ 子字符串为什么要这样做?

字符常量的C编码

c - 保存到外部文件,C

Java 字符串替换

java - g.等于位置错误?程序每次都会关闭

regex - 如何计算字符串中某个字符的频率?

javascript - 输入值逐字符反转大小写(小写/大写)

search - Elasticsearch:专门搜索括号内的单词