Comparing two characters in a string/array to see if they are the same

143 views Asked by At

I am trying to create an array and remove the repetition except for the spaces (" "). I have seen some of the methods online, but I'm trying to do it without copying. I've tried many ways but I just don't understand why my methods don't work.

This is what I've tried:

In the first one the methodology is to receive input, call function, create an arraylist, traverse through the string whilst adding each character to the arraylist, traversing through the list a second time to compare each character to the character at the first index, checking if they are equal then removing them from the arraylist

The issue seems to be "checking if they are equal then removing them from the arraylist" :

if(character.get(i).equals(character.get(k))) {
    character.remove(arr.charAt(i));                
}

And for the second one

for(int k = 0;k < characters.length;k++) {
    if(characters[i]==characters[k]) {
        System.out.print(character);                        
        character.remove(characters[i]);                    
    }   
import java.util.*;

public class NoRepeats {
    
    public static void main(String args[]) {
        System.out.print("Please enter a phrase: ");
        Scanner scanner = new Scanner(System.in);
        String input = scanner.nextLine();
        
        char[] characters = chars(input);
    }
    
    public static char[] chars(String arr) {
        ArrayList<Character> character = new ArrayList<Character>();

        for(int i = 0; i<arr.length();i++) {
            character.add(arr.charAt(i));           

            for(int k = 1; k<arr.length();k++) {
                if(character.get(i).equals(character.get(k))) {
                    character.remove(arr.charAt(i));                
                }
            }
        }
        System.out.print(character);
        return null;
    }
}
import java.util.*;

public class NoRepeats {
    
    public static void main(String args[]) {
        System.out.print("Please enter a phrase: ");
        Scanner scanner = new Scanner(System.in);
        String input = scanner.nextLine();
        //receive input
        char[] characters = chars(input);
        //call function
    }
    
    public static char[] chars(String arr) {
        ArrayList<Character> character = new ArrayList<Character>();
        //create an empty arraylist
        char[] characters = arr.toCharArray();
        
        for(int j = 0; j<characters.length;j++) {
            character.add(characters[j]);
        }
       
        for(int i = 0; i<characters.length;i++) {
            /*traverse through the orignal array adding a character to 
            the empty array list each time*/            
                for(int k = 0;k < characters.length;k++) {
                    if(characters[i]==characters[k]) {
                    System.out.print(character);                        
                    character.remove(characters[i]);                    
                }                   
            }
        }
        return null;
    }
}

Expected input:

“And I think to myself: what a wonderful world!”

Expected output:

And I thk o myself: w ru !

The first one produces this error:

Exception in thread "main" java.lang.IndexOutOfBoundsException: Index 1 out of bounds for length 1 at java.base/jdk.internal.util.Preconditions.outOfBounds(Preconditions.java:64) at java.base/jdk.internal.util.Preconditions.outOfBoundsCheckIndex(Preconditions.java:70) at java.base/jdk.internal.util.Preconditions.checkIndex(Preconditions.java:266) at java.base/java.util.Objects.checkIndex(Objects.java:359) at java.base/java.util.ArrayList.get(ArrayList.java:427) at NoRepeats.chars(NoRepeats.java:20) at NoRepeats.main(NoRepeats.java:10)

The second one produces this error:

"Exception in thread "main" java.lang.IndexOutOfBoundsException: Index 118 out of bounds for length 2 at java.base/jdk.internal.util.Preconditions.outOfBounds(Preconditions.java:64) at java.base/jdk.internal.util.Preconditions.outOfBoundsCheckIndex(Preconditions.java:70) at java.base/jdk.internal.util.Preconditions.checkIndex(Preconditions.java:266) at java.base/java.util.Objects.checkIndex(Objects.java:359) at java.base/java.util.ArrayList.remove(ArrayList.java:504) at NoRepeats.chars(NoRepeats.java:33) at NoRepeats.main(NoRepeats.java:11) "

3

There are 3 answers

0
krzydyn On

First need to formulate your algorithm in words (or kind od pseudocode). Something like this: Problem: remove duplicated chars from string except space. Solution (pseudocode):

output_string = ""
used_chars = ""
for (c : input_string) {
  if (c == ' ') output_string += c;
  else if (!used_chars.contains(c)) {
    output_string += c;
    used_chars += c;
  }
}
print(output_string)

Now you can implement this in any language you want. Implementation in java can be:

static String solution(String input_string) {
    String output_string = "";
    Set<Character> used_chars = new TreeSet<>();
    for (char c : input_string.toCharArray()) {
        if (c == ' ') output_string += c;
        else if (!used_chars.contains(c)) {
            output_string += c;
            used_chars.add(c);
        }
    }
    return output_string;
}

public static void main(String[] args) {
    System.out.println(solution("And I think to myself: what a wonderful world!"));
}
0
NoUserNoName On

Code:

package app;

import java.util.Scanner;

public class NoRepeats {
    public NoRepeats(){}

    public String scan(){
        System.out.print("Please enter a phrase: ");
        
        Scanner scanner = new Scanner(System.in);
        String read = scanner.nextLine(); //receive input
        scanner.close(); //do not forget to close
        
        return read;
    }

    public int contains(String character, char c, boolean caseInsensitive){
        int N = character.length();
        
        if(caseInsensitive) c = Character.toLowerCase(c);

        for(int i = 0; i < N; i++){
            char next = character.charAt(i);
            if(caseInsensitive) next = Character.toLowerCase(next);
            
            if(c == next) return i;
        }

        return -1;
    }

    public String getChars(String arr) {
        String character = "";

        for(int i = 0; i < arr.length(); i++){
            char next = arr.charAt(i);

            if(Character.isWhitespace(next) || contains(character, next, true) == -1) character += next;
            //else; //ignore
        }

        return character;
    }

    public static void main(String args[]) {
        NoRepeats noRepeats = new NoRepeats();

        String input = noRepeats.scan(),
               chars = noRepeats.getChars(input);

        System.out.println("String: " + chars);
    }
}

Input:

And I think to myself: what a wonderful world!

Output:

String: And I thk o myself: w  ru !
0
WJS On

You're indexing your ArrayList with i from the character array which is increasing in magnitude faster that the size of list. So you are getting an IndexOutOfBoundsException.

  • I suggest you use a HashSet to keep track of duplicates.
  • Initialize a StringBuilder to hold the result
  • If the character is not whitespace.
    • then add it to the set. If that returns false, it has been seen before so continue to the end of the for loop.
    • otherwise, add the character to StringBuilder if it is the first time seen. Since non-letter characters will never be added to the set, they will always be added to StringBuilder.
  • When done, return the array of chars. If you want to return the string instead, just do return result.toString() and change the method signature to return type String.
public static char[] chars(String arr) {
    Set<Character> seen = new HashSet<>();
    StringBuilder result = new StringBuilder();
    for (char ch : arr.toCharArray()) {
        if (!Character.isWhitespace(ch))
            if (!seen.add(Character.toLowerCase(ch))) {
                continue;
            }
        
        result.append(ch);
    }
    return result.toString().toCharArray();
}

Here is how it might work.

String input = "And I think to myself: what a wonderful world!";
char[] result = chars(input);
System.out.println(new String(result));

prints

And I thk o myself: w  ru !