java 字符串地址打印,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.

Here's my code:

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

The expected output would be: 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 + " ");

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值