abedzantout
abedzantout

Reputation: 832

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

Upvotes: 3

Views: 53792

Answers (13)

kiran
kiran

Reputation: 1

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

Upvotes: 0

kiran
kiran

Reputation: 1

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

Upvotes: 0

Mohanram G
Mohanram G

Reputation: 1

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

            }

            }




        }

    }

}

Upvotes: 0

Thu Vo
Thu Vo

Reputation: 1

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

}

Upvotes: 0

Neeraj Gupta
Neeraj Gupta

Reputation: 41

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

Upvotes: 0

CodeNinja
CodeNinja

Reputation: 19

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

Upvotes: 0

user6885473
user6885473

Reputation: 328

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

Upvotes: 0

myinterviewexp.com
myinterviewexp.com

Reputation: 42

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

Upvotes: -2

Guillaume agis
Guillaume agis

Reputation: 3774

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

Upvotes: 0

kunwar.sangram
kunwar.sangram

Reputation: 137

More fun with java 7:

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

No more cryptic numbers in regexes.

Upvotes: -1

Rupesh
Rupesh

Reputation: 2677

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

Upvotes: 0

Mena
Mena

Reputation: 48444

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

Upvotes: 43

Rich
Rich

Reputation: 865

maybe:

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

Upvotes: 4

Related Questions