Java 删除字符串中的重复字符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19730522/
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 19:45:56  来源:igfitidea点击:

Remove repeated characters in a string

javastringreplace

提问by abedzantout

I need to write a static method that takes a Stringas a parameter and returns a new Stringobtained by replacing every instance of repeated adjacent letters with a single instance of that letter without using regular expressions. For example if I enter "maaaakkee" as a String, it returns "make". I already tried the following code, but it doesn't seem to display the last character. Here's my code:

我需要编写一个静态方法,该方法将 aString作为参数并返回一个新方法,该方法通过在String不使用正则表达式的情况下用该字母的单个实例替换重复相邻字母的每个实例而获得。例如,如果我输入“maaaakkee”作为 a String,它会返回“make”。我已经尝试了以下代码,但它似乎没有显示最后一个字符。这是我的代码:

import java.util.Scanner;
public class undouble {
    public static void main(String [] args){
        Scanner console = new Scanner(System.in);
        System.out.println("enter String: ");
        String str = console.nextLine();
        System.out.println(removeSpaces(str));
    }
public static String removeSpaces(String str){
    String ourString="";
    int j = 0;
    for (int i=0; i<str.length()-1 ; i++){
        j = i+1;
        if(str.charAt(i)!=str.charAt(j)){
            ourString+=str.charAt(i);
        }

    }

    return ourString;
    }
}

采纳答案by Rupesh

The problem is with your condition. You say compare i and i+1 in each iteration and in last iteration you have both i and j pointing to same location so it will never print the last character. Try this unleass you want to use regex to achive this:

问题出在你的病情上。你说在每次迭代中比较 i 和 i+1,在最后一次迭代中你有 i 和 j 指向相同的位置,所以它永远不会打印最后一个字符。试试这个,除非你想使用正则表达式来实现这个:

EDIT:

编辑:

public  void removeSpaces(String str){
        String ourString="";
        for (int i=0; i<str.length()-1 ; i++){
            if(i==0){
                ourString = ""+str.charAt(i);
            }else{
                if(str.charAt(i-1) != str.charAt(i)){
                    ourString = ourString +str.charAt(i);
                }
            }           
        }
        System.out.println(ourString);
    }

回答by Rich

maybe:

也许:

for (int i=1; i<str.length() ; i++){
    j = i+1;
    if(str.charAt(i)!=str.charAt(j)){
        ourString+=str.charAt(i);
    }
}

回答by Mena

You could use regular expressions for that.

您可以为此使用正则表达式。

For instance:

例如:

String input = "ddooooonnneeeeee";
System.out.println(input.replaceAll("(.)\1{1,}", ""));

Output:

输出:

done

Pattern explanation:

图案说明:

  • "(.)\\1{1,}"means any character (added to group 1) followed by itself at least once
  • "$1"references contents of group 1
  • "(.)\\1{1,}"表示任何字符(添加到第 1 组)后跟它自己至少一次
  • "$1"参考第 1 组的内容

回答by kunwar.sangram

More fun with java 7:

使用 Java 7 更有趣:

System.out.println("11223344445555".replaceAll("(?<nums>.+)\k<nums>+","${nums}"));

No more cryptic numbers in regexes.

正则表达式中不再有神秘数字。

回答by GuillaumeAgis

if you cannot use replace or replaceAll, here is an alternative. O(2n), O(N) for stockage and O(N) for creating the string. It removes all repeated chars in the string put them in a stringbuilder.

如果您不能使用 replace 或 replaceAll,这里有一个替代方法。O(2n)、O(N) 用于库存和 O(N) 用于创建字符串。它删除字符串中所有重复的字符,将它们放入字符串生成器中。

input : abcdef , output : abcdef

输入:abcdef,输出:abcdef

input : aabbcdeef, output : cdf

输入:aabbcdeef,输出:cdf

private static String remove_repeated_char(String str)
{
    StringBuilder result = new StringBuilder();
    HashMap<Character, Integer> items = new HashMap<>();

    for (int i = 0; i < str.length(); i++)
    {
        Character current = str.charAt(i);
        Integer ocurrence = items.get(current);
        if (ocurrence == null)
            items.put(current, 1);
        else
            items.put(current, ocurrence + 1);
    }

    for (int i = 0; i < str.length(); i++)
    {
        Character current = str.charAt(i);
        Integer ocurrence = items.get(current);
        if (ocurrence == 1)
            result.append(current);
    }
    return result.toString();
}

回答by myinterviewexp.com

public static String removeDuplicates(String str) {

公共静态字符串 removeDuplicates(String str) {

    String str2 = "" + str.charAt(0);
    for (int i = 1; i < str.length(); i++) {
        if (str.charAt(i - 1) == str.charAt(i) && i != 0) {
            continue;
        }
        str2 = str2 + str.charAt(i);
    }
    return str2;
}

回答by user6885473

import java.util.*;
public class string2 {

    public static void main(String[] args) {

        //removes repeat character from array
        Scanner sc=new Scanner(System.in);
        StringBuffer sf=new StringBuffer();
        System.out.println("enter a string");
        sf.append(sc.nextLine());
        System.out.println("string="+sf);
        int i=0;

        while( i<sf.length())
        {
            int j=1+i;
            while(j<sf.length())
            {   

                if(sf.charAt(i)==sf.charAt(j))
                {
                    sf.deleteCharAt(j);
                }
                else
                {
                    j=j+1;
                }
            }
            i=i+1;
        }

        System.out.println("string="+sf);
    }
}

回答by CodeNinja

Input AABBBccDDD, Output BD Input ABBCDDA, Outout C

输入 AABBccDDD,输出 BD 输入 ABBCDDA,输出 C

    private String reducedString(String s){
    char[] arr = s.toCharArray();
    String newString = "";
    Map<Character,Integer> map = new HashMap<Character,Integer>();
    map.put(arr[0],1);
    for(int index=1;index<s.length();index++)
    {
        Character key = arr[index];   
        int value;
        if(map.get(key) ==null)
        {
            value =0;
        }
        else 
        {
            value = map.get(key);
        }

        value = value+1;
        map.put(key,value);
    }
    Set<Character> keyset = map.keySet();

    for(Character c: keyset)
    {
        int value = map.get(c);

        if(value%2 !=0)
        {
            newString+=c;
        }
    }

    newString = newString.equals("")?"Empty String":newString;
    return newString;
}

回答by Neeraj Gupta

public class RemoveDuplicateCharecterInString {
    static String input = new String("abbbbbbbbbbbbbbbbccccd");
    static String output = "";
    public static void main(String[] args)
 {
        // TODO Auto-generated method stub

        for (int i = 0; i < input.length(); i++) {
            char temp = input.charAt(i);
            boolean check = false;

            for (int j = 0; j < output.length(); j++) {
                if (output.charAt(j) == input.charAt(i)) {
                    check = true;
                }
            }
            if (!check) {
                output = output + input.charAt(i);
            }
        }
        System.out.println("  " + output);
    }
}

Answer : abcd

答案:abcd

回答by Thu Vo

public class RepeatedChar {

    public static void main(String[] args) {
        String rS = "maaaakkee";
        String outCome= rS.charAt(0)+"";
        int count =0;
        char [] cA =rS.toCharArray();
        for(int i =0; i+1<cA.length; ++i) {
            if(rS.charAt(i) != rS.charAt(i+1)) {
                outCome += rS.charAt(i+1);
            }
        }

        System.out.println(outCome);
    }

}