3

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. 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:

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;
    }
}
Justin
  • 24,288
  • 12
  • 92
  • 142
abedzantout
  • 802
  • 4
  • 15
  • 28

13 Answers13

43

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" references contents of group 1
Mena
  • 47,782
  • 11
  • 87
  • 106
  • 2
    Ugh; you beat me to it. [Java Regex Tutorial](http://www.vogella.com/articles/JavaRegularExpressions/article.html) has a good explanation of how to use regex. – Justin Nov 01 '13 at 16:08
  • 4
    Nice regex, but why `{1,}` if you can use `+`? – Pshemo Nov 01 '13 at 16:10
  • 1
    thank you, unfortunately we are still not allowed to use such expressions, i need to stick to the for loop. but great information i'll add it to my notes :) – abedzantout Nov 01 '13 at 16:10
  • This answer don't achieve the objective because for the given example: String input = "ddooooonnneeeeee"; The output should be: "dooonneee" . THe requisite says : every two repeated letters will became one. Not more than two. If i get it right. – Leonardo Pugliese Nov 01 '13 at 16:13
  • @LeonardoPugliese OP says "**every** instance of repeated adjacent letters with a single instance of that letter". – Mena Nov 01 '13 at 16:15
  • @LeonardoPugliese well, in OP we can see `For example if I enter "maaaakkee" as a String, it returns "make"` so it seems that this answer is correct. – Pshemo Nov 01 '13 at 16:16
  • 2
    @Predator44 you're welcome! Sorry to hear you can't use it :( – Mena Nov 01 '13 at 16:16
  • @LeonardoPugliese, i think you misunderstood the question, what Mena wrote actually gives the required output. – abedzantout Nov 01 '13 at 16:16
  • 1
    @Pshemo Thanks. By the way you can totally use the `+`. Not sure why I turned out to use `{1,}` instead, but well, it's equivalent within this context I guess. – Mena Nov 01 '13 at 16:17
  • Oh, sorry guys. My fault. – Leonardo Pugliese Nov 01 '13 at 16:31
  • @LeonardoPugliese no worries :) – Mena Nov 01 '13 at 16:34
  • Clear efficient answer +1 :) – zx81 Jun 09 '14 at 00:37
4

maybe:

for (int i=1; i<str.length() ; i++){
    j = i+1;
    if(str.charAt(i)!=str.charAt(j)){
        ourString+=str.charAt(i);
    }
}
Rich
  • 867
  • 7
  • 12
  • it gives me an error unless i replace str.lenthg() by str.lenthg()-1 – abedzantout Nov 01 '13 at 16:05
  • 1) characters are indexed from `0` till `length-1` 2) if you are adding to result only left character from two that are not equal then in case `"abb"` you will skip `"b"` 3) don't use `+=` operator in loop on result Strings, instead create `StringBuilder` before loop and `append(additionalPart)` to it inside loop. Then you can get result using `toString` method. – Pshemo Nov 01 '13 at 16:32
0

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:

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);
    }
Rupesh
  • 2,627
  • 1
  • 28
  • 42
  • The best way to do this is using StringBuilder. Appending to the end of a string `str = string + end` takes much longer than adding to a StringBuilder. https://stackoverflow.com/questions/4989091/removing-duplicates-from-a-string-in-java – Tillson Jun 08 '19 at 06:44
0

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.

input : abcdef , output : abcdef

input : aabbcdeef, output : 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();
}
Guillaume agis
  • 3,756
  • 1
  • 20
  • 24
0
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);
    }
}
Pang
  • 9,564
  • 146
  • 81
  • 122
user6885473
  • 298
  • 1
  • 5
  • 20
  • You could explain your code instead of just dumping it here. It's also overly complicated --- why 2 loops, why a `StringBuffer` and deleting instead of copying non-duplicated characters? – Robert Sep 28 '16 at 02:36
0

Input AABBBccDDD, Output BD Input ABBCDDA, Outout 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;
}
CodeNinja
  • 19
  • 4
0
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

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

}
Black Mamba
  • 13,632
  • 6
  • 82
  • 105
Thu Vo
  • 1
0

TO WRITE JAVA PROGRAM TO REMOVE REPEATED CHARACTERS:

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

            }

            }




        }

    }

}
Lovepreet Singh
  • 4,792
  • 1
  • 18
  • 36
0
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);
anothernode
  • 5,100
  • 13
  • 43
  • 62
kiran
  • 1
  • 1
  • Please do not post just some piece of code as answer but also explain _why_ this code works (in contrast to that of the question) – Würgspaß Aug 10 '18 at 11:56
0
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);
    }
kiran
  • 1
  • 1
-1

More fun with java 7:

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

No more cryptic numbers in regexes.

  • The OP said, “without using regular expressions”, so this solution isn’t an answer to the question. Aside from that, the solution is wrong because it would replace “nonono” with “no”. – Chriki May 01 '16 at 16:26
-2

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;
}
  • 1
    This solution is not correct. It doesn’t only remove repeated _adjacent_ characters. For example, “meeeekeee” becomes “mek”. – Chriki May 01 '16 at 16:20
  • Can you expand on why you feel this is a good answer, and perhap explain what the proposed solution is doing? – Ro Yo Mi May 02 '16 at 02:10