有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

我正在编写一个程序,将打印字符串中的唯一字符(通过扫描仪输入)。我创建了一个方法,试图实现这一点,但我不断得到不重复的字符,而不是字符串特有的字符。我只想要独一无二的字母

这是我的代码:

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


共 (3) 个答案

  1. # 1 楼答案

    应用接吻原则怎么样:

    public static void uniqueCharacters(String test) {
        System.out.println(test.chars().distinct().mapToObj(c -> String.valueOf((char)c)).collect(Collectors.joining()));
    }
    
  2. # 2 楼答案

    这是一个面试问题。找出字符串的所有唯一字符。 以下是完整的解决方案。代码本身是不言自明的

    public class Test12 {
        public static void main(String[] args) {
            String a = "ProtijayiGiniGina";
    
            allunique(a);
        }
    
        private static void allunique(String a) {
            int[] count = new int[256];// taking count of characters
            for (int i = 0; i < a.length(); i++) {
                char ch = a.charAt(i);
                count[ch]++;
            }
    
            for (int i = 0; i < a.length(); i++) {
                char chh = a.charAt(i);
                // character which has arrived only one time in the string will be printed out
                if (count[chh] == 1) {
                    System.out.println("index => " + i + " and unique character => " + a.charAt(i));
    
                }
            }
    
        }// unique
    
    }
    

    在Python中:

    def firstUniqChar(a):
        count = [0] *256
        for i in a: count[ord(i)] += 1
        element = ""
    
        for item in a:
            if (count[ord(item)] == 1):
                element = item;
                break;
        return element        
    
    
    a = "GiniGinaProtijayi";
    print(firstUniqChar(a)) # output is P
    
  3. # 3 楼答案

    根据所需的输出,您必须替换一个最初已添加的字符,然后再添加一个重复的字符,因此:

    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 + " ");
    
    }