如何从java中的字符串中删除重复字符?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19578436/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 18:28:40  来源:igfitidea点击:

How to remove duplicate character from a string in java?

javacharacterduplicate-removalmode

提问by ToonLink

In my program, the user enters a string, and it first finds the largest mode of characters in the string. Next, my program is supposed to remove all duplicates of a character in a string, (user input: aabc, program prints: abc) which I'm not entirely certain on how to do. I can get it to remove duplicates from some strings, but not all. For example, when the user puts "aabc" it will print "abc", but if the user puts "aabbhh", it will print "abbhh." Also, before I added the removeDup method to my program, it would only print the maxMode once, but after I added the removeDup method, it began to print the maxMode twice. How do I keep it from printing it twice?

在我的程序中,用户输入一个字符串,它首先找到字符串中最大的字符模式。接下来,我的程序应该删除字符串中一个字符的所有重复项(用户输入:aabc,程序打印:abc),我不完全确定该怎么做。我可以让它从某些字符串中删除重复项,但不是全部。例如,当用户输入“aabc”时,它会打印“abc”,但如果用户输入“aabbhh”,它会打印“abbhh”。此外,在我将 removeDup 方法添加到我的程序之前,它只会打印一次 maxMode,但是在我添加 removeDup 方法之后,它开始打印两次 maxMode。如何防止它打印两次?

Note: I cannot convert the strings to an array.

注意:我无法将字符串转换为数组。

import java.util.Scanner;

public class JavaApplication3 {
static class MyStrings {
    String s;

void setMyStrings(String str) {
    s = str;    
}

int getMode() {
        int i;
        int j;
        int count = 0;
        int maxMode = 0, maxCount = 1;
        for (i = 0; i< s.length(); i++) {
            maxCount = count;
            count = 0;
            for (j = s.length()-1; j >= 0; j--) {
                if (s.charAt(j) == s.charAt(i))
                    count++;
                if (count > maxCount){
                    maxCount = count;
                    maxMode = i;
                }
            }       
        }
        System.out.println(s.charAt(maxMode)+" = largest mode");

      return maxMode;  
}

    String removeDup() {
       getMode();
       int i;
       int j;
       String rdup = "";

       for (i = 0; i< s.length(); i++) {
           int count = 1;
           for (j = 0; j < rdup.length(); j++) {
               if (s.charAt(i) == s.charAt(j)){
                    count++;
               }
           }
           if (count == 1){
               rdup += s.charAt(i);
               }
           } 
           System.out.print(rdup);
           System.out.println();
           return rdup;
       }


}

public static void main (String[] args) {
Scanner in = new Scanner(System.in);
MyStrings setS = new MyStrings();

    String s;

            System.out.print("Enter string:");
            s = in.nextLine();

            setS.setMyStrings(s);
            setS.getMode();
            setS.removeDup();


}

}

回答by Christian Ternus

Welcome to StackOverflow!

欢迎使用 StackOverflow!

You're calling getMode()both outside and inside of removeDup(), which is why it's printing it twice.

getMode()同时调用了 的外部和内部removeDup(),这就是它打印两次的原因。

In order to remove allduplicates, you'll have to call removeDup()over and over until all the duplicates are gone from your string. Right now you're only calling it once.

为了删除所有重复项,您必须removeDup()一遍又一遍地调用,直到所有重复项从您的字符串中消失。现在你只调用一次。

How might you do that? Think about how you're detecting duplicates, and use that as the end condition for a whileloop or similar.

你怎么能这样做?想想您如何检测重复项,并将其用作while循环或类似的结束条件。

Happy coding!

快乐编码!

回答by TANMANA

Try this method...should work fine!

试试这个方法……应该没问题!

String removeDup() 
{         
   getMode();
   int i;
   int j;
   String rdup = "";

   for (i = 0; i< s.length(); i++) {
       int count = 1;

       for (j = i+1; j < s.length(); j++) {
           if (s.charAt(i) == s.charAt(j)) {
                count++;
           }
       }
       if (count == 1){
           rdup += s.charAt(i);
       }
   } 
     //  System.out.print(rdup);
   System.out.println();
   return rdup;
}

回答by M2je

I think an optimized version which supports ASCII codes can be like this:

我认为支持 ASCII 代码的优化版本可以是这样的:

public static void main(String[] args) {
    System.out.println(removeDups("*PqQpa abbBBaaAAzzK zUyz112235KKIIppP!!QpP^^*Www5W38".toCharArray()));
}
public static String removeDups(char []input){
    long ocr1=0l,ocr2=0l,ocr3=0;
    int index=0;
    for(int i=0;i<input.length;i++){
        int val=input[i]-(char)0;
        long ocr=val<126?val<63?ocr1:ocr2:ocr3;
        if((ocr& (1l<<val))==0){//not duplicate
            input[index]=input[i];
            index++;
        }
        if(val<63)
            ocr1|=(1l<<val);
        else if(val<126)
            ocr2|=(1l<<val);
        else 
            ocr3|=(1l<<val);
    }
    return new String(input,0,index);
}

please keep in mind that each of orc(s) represent a mapping of a range of ASCII characters and each java long variable can grow as big as (2^63) and since we have 128 characters in ASCII so we need three ocr(s) which basically maps the occurrences of the character to a long number.

请记住,每个 orc(s) 代表一系列 ASCII 字符的映射,每个 java long 变量可以增长到 (2^63) 大,因为我们有 128 个 ASCII 字符,所以我们需要三个 ocr(s) ) 基本上将字符的出现映射到一个长数字。

  • ocr1: (char)0 to (char)62
  • ocr2: (char)63 to (char)125
  • ocr3: (char)126 to (char)128
  • ocr1: (char)0 到 (char)62
  • ocr2: (char)63 到 (char)125
  • ocr3: (char)126 到 (char)128

Now if a duplicate was found the

现在,如果发现重复

(ocr& (1l<<val)) 

will be greater than zero and we skip that char and finally we can create a new string with the size of index which shows last non duplicate items index. You can define more orc(s) and support other character-sets if you want.

将大于零,我们跳过该字符,最后我们可以创建一个具有索引大小的新字符串,该字符串显示最后一个非重复项的索引。如果需要,您可以定义更多的兽人并支持其他字符集。

回答by Santanu

Can use HashSet as well as normal for loops:

可以使用 HashSet 以及普通的 for 循环:

public class RemoveDupliBuffer 
{
public static String checkDuplicateNoHash(String myStr)
{
    if(myStr == null)
        return null;
    if(myStr.length() <= 1)
        return myStr;

    char[] myStrChar = myStr.toCharArray();
    HashSet myHash = new HashSet(myStrChar.length);
    myStr = "";

    for(int i=0; i < myStrChar.length ; i++)
    {
        if(! myHash.add(myStrChar[i]))
        {

        }else{
            myStr += myStrChar[i];
        }
    }
    return myStr;
}

public static String checkDuplicateNo(String myStr) 
{
    // null check
    if (myStr == null)
        return null;
    if (myStr.length() <= 1)
        return myStr;

    char[] myChar = myStr.toCharArray();
    myStr = "";
    int tail = 0;
    int j = 0;

    for (int i = 0; i < myChar.length; i++) 
    {
        for (j = 0; j < tail; j++)
        {
            if (myChar[i] == myChar[j])
            {
                break;
            }
        }
        if (j == tail)
        {
            myStr += myChar[i];
            tail++;
        }
    }

    return myStr;
}

public static void main(String[] args) {
    String myStr = "This is your String";
    myStr = checkDuplicateNo(myStr);
    System.out.println(myStr);
}

回答by Jarvis_Tomahawk

Try this simple answer- works well for simple character string accepted as user input:

试试这个简单的答案 - 适用于作为用户输入接受的简单字符串:

import java.util.Scanner;

导入 java.util.Scanner;

public class string_duplicate_char {

公共类 string_duplicate_char {

String final_string = "";

public void inputString() {

    //accept string input from user
    Scanner user_input = new Scanner(System.in);
    System.out.println("Enter a String to remove duplicate Characters : \t");
    String input = user_input.next();
    user_input.close();

    //convert string to char array
    char[] StringArray = input.toCharArray();
    int StringArray_length = StringArray.length;

    if (StringArray_length < 2) {
        System.out.println("\nThe string with no duplicates is: "
                + StringArray[1] + "\n");
    } else {
        //iterate over all elements in the array
        for (int i = 0; i < StringArray_length; i++) {

            for (int j = i + 1; j < StringArray_length; j++) {

                if (StringArray[i] == StringArray[j]) {
                    int temp = j;//set duplicate element index

                    //delete the duplicate element by copying the adjacent elements by one place
                    for (int k = temp; k < StringArray_length - 1; k++) {
                        StringArray[k] = StringArray[k + 1];
                    }
                    j++;
                    StringArray_length--;//reduce char array length

                }
            }

        }

    }

    System.out.println("\nThe string with no duplicates is: \t");

    //print the resultant string with no duplicates
    for (int x = 0; x < StringArray_length; x++) {

        String temp= new StringBuilder().append(StringArray[x]).toString();
        final_string=final_string+temp;
    }
    System.out.println(final_string);

}

public static void main(String args[]) {

    string_duplicate_char object = new string_duplicate_char();
    object.inputString();

}

}

}

回答by Jarvis_Tomahawk

Another easy solution to clip the duplicate elements in a string using HashSet and ArrayList :

使用 HashSet 和 ArrayList 剪辑字符串中重复元素的另一个简单解决方案:

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Scanner;

public class sample_work {

    public static void main(String args[]) {

        String input = "";

        System.out.println("Enter string to remove duplicates: \t");
        Scanner in = new Scanner(System.in);
        input = in.next();
        in.close();

        ArrayList<Character> String_array = new ArrayList<Character>();
        for (char element : input.toCharArray()) {
            String_array.add(element);
        }

        HashSet<Character> charset = new HashSet<Character>();
        int array_len = String_array.size();
        System.out.println("\nLength of array = " + array_len);

        if (String_array != null && array_len > 0) {
            Iterator<Character> itr = String_array.iterator();
            while (itr.hasNext()) {
                Character c = (Character) itr.next();
                if (charset.add(c)) {

                } else {
                    itr.remove();
                    array_len--;
                }
            }
        }
        System.out.println("\nThe new string with no duplicates: \t");
        for (int i = 0; i < array_len; i++) {
            System.out.println(String_array.get(i).toString());
        }
    }

}

回答by Shubham Sharma

your can use this simple code and understand how to remove duplicates values from string.I think this is the simplest way to understand this problem.

您可以使用这个简单的代码并了解如何从字符串中删除重复值。我认为这是理解此问题的最简单方法。

class RemoveDup {

类 RemoveDup {

static int l;
public String dup(String str)
{

l=str.length();
System.out.println("length"+l);
char[] c=str.toCharArray();

for(int i=0;i<l;i++)
{

    for(int j=0;j<l;j++)
    {
        if(i!=j)
        {   
        if(c[i]==c[j])
        {
            l--;
            for(int k=j;k<l;k++)
            {
        c[k]=c[k+1];
            }
            j--;
        }
        }
    }


}

System.out.println("after concatination lenght:"+l);
StringBuilder sd=new StringBuilder();
for(int i=0;i<l;i++)
{
    sd.append(c[i]);

}
str=sd.toString();
return str;
}



public static void main(String[] ar)
{
RemoveDup obj=new RemoveDup();
Scanner sc=new Scanner(System.in);
String st,t;
System.out.println("enter name:");
st=sc.nextLine();
sc.close();
t=obj.dup(st);
System.out.println(t);
}

}

}

回答by Thenn Arasu

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package javaapplication26;

import java.util.*;

/**
 *
 * @author THENNARASU
 */
public class JavaApplication26 {

    public static void main(String[] args) {


   int i,j,k=0,count=0,m;

    char a[]=new char[10];

       char b[]=new char[10]; 

    Scanner ob=new Scanner(System.in);

    String str;

    str=ob.next();

    a=str.toCharArray();

    int c=str.length();


    for(j=0;j<c;j++)

   {

        for(i=0;i<j;i++)

        {

            if(a[i]==a[j])

            {

                count=1;


            }

        }

         if(count==0)

        {

            b[k++]=a[i];

        }

        count=0;

    }

   for(m=0;b[m]!='
import java.util.*;

public class First {

public static void main(String arg[])
{
    Scanner sc= new Scanner(System.in);
    StringBuilder s=new StringBuilder(sc.nextLine());        
    //String s=new String();
    for(int i=0;i<s.length();i++){
        String a=s.substring(i, i+1);
        while(s.indexOf(a)!=s.lastIndexOf(a)){s.deleteCharAt(s.lastIndexOf(a));}
    }
    System.out.println(s.toString());
}
}
';m++) { System.out.println(b[m]); } } }

回答by Aman Dhingra

Shouldn't this be an easier way? Also, i'm still learning.

这不应该是一个更简单的方法吗?另外,我还在学习中。

 public String removeMultipleOcuranceOfChar(String string, int numberOfChars){
     char[] word1 = string.toCharArray();
     char[] word2 = string.toCharArray();
     int count=0;         
     StringBuilder builderNoDups = new StringBuilder();
     StringBuilder builderDups = new StringBuilder();

     for(char x: word1){             
         for(char y : word2){
             if (x==y){
                 count++;
             }//end if                  
         }//end inner loop            
         System.out.println(x + " occurance: " + count );
         if (count ==numberOfChars){
             builderNoDups.append(x);                 
         }else{
             builderDups.append(x);
         }//end if else
         count = 0;             
     }//end outer loop
     return String.format("Number of identical chars to be in or out of input string: "
             + "%d\nOriginal word: %s\nWith only %d identical chars: %s\n"
             + "without %d identical chars: %s",
             numberOfChars,string,numberOfChars, builderNoDups.toString(),numberOfChars,builderDups.toString());
}

回答by Shimrod

i wrote this program. Am using 2 char arrays instead. You can define the number of duplicate chars you want to eliminate from the original string and also shows the number of occurances of each character in the string.

我写了这个程序。我改用 2 个字符数组。您可以定义要从原始字符串中消除的重复字符的数量,还可以显示字符串中每个字符出现的次数。

##代码##