Java:在字符串中打印一个唯一的字符 [英] Java: Print a unique character in a string

查看:284
本文介绍了Java:在字符串中打印一个唯一的字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个程序,用于打印字符串中的唯一字符(通过扫描仪输入)。我已经创建了一个尝试完成此操作的方法,但我不断获取不重复的字符,而不是字符串唯一的字符(或字符)。我只想要这些独特的字母。

I'm writing a program that will print the unique character in a string (entered through a scanner). I've created a method that tries to accomplish this but I keep getting characters that are not repeats, instead of a character (or characters) that is unique to the string. I want the unique letters only.

这是我的代码:

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

   }
}            

这里的示例输出如上代码:

And here's sample output with the above code:

Enter a word: 
nreena
nrea 

预期输出为: ra

推荐答案

根据您所需的输出,您必须替换最初在以后重复时添加的字符,因此:

Based on your desired output, you have to replace a character that initially has been already added when it has a duplicated later, so:

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:在字符串中打印一个唯一的字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆