简体   繁体   English

删除字符串中的重复字符

[英]Remove repeated characters in a string

I need to write a static method that takes a String as a parameter and returns a new String obtained by replacing every instance of repeated adjacent letters with a single instance of that letter without using regular expressions. 我需要编写一个静态方法,该方法将String作为参数,并返回一个新的String ,该String是通过将该重复的相邻字母的每个实例替换为该字母的单个实例而不使用正则表达式而获得的。 For example if I enter "maaaakkee" as a String , it returns "make". 例如,如果我输入“maaaakkee”作为String ,则返回“make”。 I already tried the following code, but it doesn't seem to display the last character. 我已经尝试了以下代码,但它似乎没有显示最后一个字符。 Here's my code: 这是我的代码:

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;
    }
}

You could use regular expressions for that. 你可以使用正则表达式。

For instance: 例如:

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

Output: 输出:

done

Pattern explanation: 模式说明:

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

maybe: 也许:

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

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. 你说在每次迭代中比较i和i + 1,在最后一次迭代中你有i和j指向同一个位置,所以它永远不会打印最后一个字符。 Try this unleass you want to use regex to achive this: 试试这个unleass你想使用正则表达式来实现这个:

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);
    }

if you cannot use replace or replaceAll, here is an alternative. 如果你不能使用replace或replaceAll,这里有一个替代方案。 O(2n), O(N) for stockage and O(N) for creating the string. O(2n),O(N)用于储存,O(N)用于创建字符串。 It removes all repeated chars in the string put them in a stringbuilder. 它删除字符串中所有重复的字符,将它们放在stringbuilder中。

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();
}
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);
    }
}

Input AABBBccDDD, Output BD Input ABBCDDA, Outout C 输入AABBBccDDD,输出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;
}
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

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);
    }

}

TO WRITE JAVA PROGRAM TO REMOVE REPEATED CHARACTERS: 编写JAVA程序以删除重复的字符:

package replace;

public class removingrepeatedcharacters 

{

public static void main(String...args){
        int i,j=0,count=0;

        String str="noordeen";
        String str2="noordeen";
        char[] ch=str.toCharArray();
        for(i=0;i<=5;i++)
        {
            count=0;
            for(j=0;j<str2.length();j++)
            {
            if(ch[i]==str2.charAt(j))
            {
                count++;
                System.out.println("at the index "+j +"position  "+ch[i]+    "+ count is"+count);
                if(count>=2){
                    str=str2;
                    str2=str.replaceFirst(Character.toString(ch[j]),Character.toString(' '));
            }

                System.out.println("after replacing    "          +str2);   

            }

            }




        }

    }

}
String outstr = "";
String outstring = "";
for(int i = 0; i < str.length() - 1; i++) {
    if(str.charAt(i) != str.charAt(i + 1)) {
        outstr = outstr + str.charAt(i);
    }
    outstring = outstr + str.charAt(i);         
}
System.out.println(outstring);
public static void remove_duplicates(String str){
    String outstr="";
    String outstring="";
    for(int i=0;i<str.length()-1;i++) {
    if(str.charAt(i)!=str.charAt(i+1)) {
        outstr=outstr+str.charAt(i);
        }
        outstring=outstr+str.charAt(i);
        }
        System.out.println(outstring);
    }

More fun with java 7: 使用java 7更有趣:

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

No more cryptic numbers in regexes. 在正则表达式中没有更多神秘的数字。

public static String removeDuplicates(String str) { public static String 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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM