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

8
我正在编写一个程序,它将打印字符串中的唯一字符(通过扫描器输入)。我创建了一个方法来尝试完成这个任务,但我一直得到不是重复字符的字符,而不是字符串中唯一的字符(或字符)。我只想要独特的字母。
这是我的代码:
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

“nreena”的预期输出是什么? - developer
1
但是 e 是一个重复的字符,你仍然在输出中得到了它。你期望的输出是 ra 吗? - RaminS
无论如何,我会像这样做 char[] array = test.toCharArray(); 然后循环遍历 array 中的每个字母,如果没有匹配项,则执行 temp = temp + test.charAt(i); - RaminS
是的,期望的输出应该是“ra”。 - Dextra
一旦您添加了一个字符,即使找到它的多个出现,也不会删除现有的字符。 - Naman
20个回答

0

公共类Program02 {

public static void main(String[] args)
{   
    String inputString = "abhilasha";
    
    for (int i = 0; i < inputString.length(); i++)
    {
        for (int j = i + 1; j < inputString.length(); j++)
        {
            if(inputString.toCharArray()[i] == inputString.toCharArray()[j])
            {
                inputString = inputString.replace(String.valueOf(inputString.charAt(j)), "");
            }
        }
    }
    
    System.out.println(inputString);
}

}


目前你的回答不够清晰,请编辑并添加更多细节,以帮助其他人理解它如何回答问题。你可以在帮助中心找到有关如何编写好答案的更多信息。 - Community

0
import java.util.*;
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){
     for(int i=0;i<test.length();i++){
         if(test.lastIndexOf(test.charAt(i))!=i)
         test=test.replaceAll(String.valueOf(test.charAt(i)),"");
     }
  System.out.println(test);
}

}

请在您的回答中提供更多细节。目前的写法让人难以理解您的解决方案。 - Community

0
我会将字符串的所有字符存储在一个数组中,然后循环遍历该数组以检查当前字符是否出现了多次。如果没有,则将其添加到临时变量中。
public static void uniqueCharacters(String test) {
    String temp = "";
    char[] array = test.toCharArray();
    int count; //keep track of how many times the character exists in the string

    outerloop: for (int i = 0; i < test.length(); i++) {
        count = 0; //reset the count for every new letter
        for(int j = 0; j < array.length; j++) {
            if(test.charAt(i) == array[j])
                count++;
            if(count == 2){
                count = 0;
                continue outerloop; //move on to the next letter in the string; this will skip the next two lines below
            }
        }
        temp += test.charAt(i);
        System.out.println("Adding.");
    }    
    System.out.println(temp);
}

我已经添加了一些注释以增加详细信息。


0

这个怎么样?:)

for (int i=0; i< input.length();i++)
    if(input.indexOf(input.charAt(i)) == input.lastIndexOf(input.charAt(i)))
        System.out.println(input.charAt(i) + "  is unique");

0

这个字符串算法用于打印字符串中的唯一字符。它的运行时间为O(n),其中n是字符串的长度。它仅支持ASCII字符。

static String printUniqChar(String s) {
    StringBuilder buildUniq = new StringBuilder();
    boolean[] uniqCheck = new boolean[128];
    for (int i = 0; i < s.length(); i++) {
        if (!uniqCheck[s.charAt(i)]) {
            uniqCheck[s.charAt(i)] = true;
            if (uniqCheck[s.charAt(i)])
                buildUniq.append(s.charAt(i));
        }
    }

仅提供代码答案并不鼓励,因为它们对于未来的读者提供的信息不多,请在您编写的内容中提供一些解释。 - WhatsThePoint

0
这里的str将成为您要查找唯一字符的字符串。
function getUniqueChars(str){
let uniqueChars = '';
for(let i = 0; i< str.length; i++){
  for(let j= 0; j< str.length; j++) {
    if(str.indexOf(str[i]) === str.lastIndexOf(str[j])) {
       uniqueChars += str[i];
     }
   }
 }
 return uniqueChars;    

}


0
public class UniqueCharactersInString {


 public static void main(String []args){

    String input = "aabbcc";
    String output = uniqueString(input);

    System.out.println(output);
 }

 public static String uniqueString(String s){
     HashSet<Character> uniques = new HashSet<>();
     uniques.add(s.charAt(0));
     String out = "";
     out += s.charAt(0);

     for(int i =1; i < s.length(); i++){
         if(!uniques.contains(s.charAt(i))){
             uniques.add(s.charAt(i));
             out += s.charAt(i);
         }
     }
     return out;
 }
}

这个答案有哪些低效之处?它与其他答案相比如何?


仅提供代码的答案是不被鼓励的。为了帮助未来的读者,请解释你正在做什么! - itsmysterybox

0

根据您所需的输出,您可以用空白字符替换每个已存在的字符。

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);
      } else {
         temp.replace(String.valueOf(temp.charAt(i)), "");
      }
 }

System.out.println(temp + " ");

}


0
public void uniq(String inputString) {
    String result = "";
    int inputStringLen = inputStr.length();
    int[] repeatedCharacters = new int[inputStringLen];
    char inputTmpChar;
    char tmpChar;

    for (int i = 0; i < inputStringLen; i++) {
        inputTmpChar = inputStr.charAt(i);
        for (int j = 0; j < inputStringLen; j++) {
            tmpChar = inputStr.charAt(j);
            if (inputTmpChar == tmpChar)
                repeatedCharacters[i]++;
        }
    }

    for (int k = 0; k < inputStringLen; k++) { 
        inputTmpChar = inputStr.charAt(k);
        if (repeatedCharacters[k] == 1)
            result = result + inputTmpChar + " ";
    }

    System.out.println ("Unique characters: " + result);
}

在第一个循环中,我计算字符串中字符重复的次数。
在第二行中,我寻找只出现过一次的字符。


0

package extra;

public class TempClass {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        String abcString="hsfj'pwue2hsu38bf74sa';fwe'rwe34hrfafnosdfoasq7433qweid";
        char[] myCharArray=abcString.toCharArray();
        TempClass mClass=new TempClass();

        mClass.countUnique(myCharArray);
        mClass.countEach(myCharArray);
    }
    /**
     * This is the program to find unique characters in array.
     * @add This is nice.
     * */
    public void countUnique(char[] myCharArray) {
        int arrayLength=myCharArray.length;
        System.out.println("Array Length is: "+arrayLength);
        char[] uniqueValues=new char[myCharArray.length];
        int uniqueValueIndex=0;
        int count=0;
        for(int i=0;i<arrayLength;i++) {
            for(int j=0;j<arrayLength;j++) {
                if (myCharArray[i]==myCharArray[j] && i!=j) {
                    count=count+1;
                }
            }
            if (count==0) {
                uniqueValues[uniqueValueIndex]=myCharArray[i];
                uniqueValueIndex=uniqueValueIndex+1;
                count=0;
            }
            count=0;
        }
        for(char a:uniqueValues) {
            System.out.println(a);
        }
    }
    /**
     * This is the program to find count each characters in array.
     * @add This is nice.
     * */
    public void countEach(char[] myCharArray) {

    }
}


1
添加一份说明,以帮助用户理解问题的实际所在。 - Sami Ahmed Siddiqui

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接