javastringlistarraylistcompareto

Comparing two Strings if word spacing and capitalization do not matter-Java


What I want to do is create a method that takes two objects as input of type String. The method will return logical truth if both strings are the same (word spacing and capitalization do not matter). I thought to split String, make an Array of elements, add each element to List and then compare each element to space and remove it from List. At the end use a compareToIgnoreCase() method. I stopped on removing space from List for string2. It works to string1List and doesn't work to string2List, I'm wondering why?? :(

I will be grateful for help, I spend a lot of time on it and I'm stuck. Maybe someone know a better solution.

import java.util.ArrayList;
import java.util.List;

public class Strings {
public static void main(String[] args) {


    String string1 = "This is a first string";
    String string2 = "this is   a first string";


    String[] arrayOfString1 = string1.split("");
    List<String> string1List = new ArrayList<>();


    for (int i = 0; i < arrayOfString1.length; ++i) {
        string1List.add(arrayOfString1[0 + i]);
    }

    String[] arrayOfString2 = string2.split("");
    List<String> string2List = new ArrayList<>();

    for (int i = 0; i < arrayOfString2.length; ++i) {
        string2List.add(arrayOfString2[0 + i]);
    }

    for (int i = 0; i < string1List.size(); ++i) {
        String character = string1List.get(0 + i);
        if (character.equals(" ")) {
            string1List.remove(character);
        }
    }
    for (int i = 0; i < string2List.size(); ++i) {
        String character = string2List.get(0 + i);
        if (character.equals(" ")) {
            string2List.remove(character);
        }
    }
    System.out.println(string2List.size());
}

}


Solution

  • Your problem has nothing to do with spaces. You can replace them with any other character (for example "a") to test this. Therefore, removing spaces in any of the methods given above will not improve your code.

    The source of the problem is iterating the list with the for command. When you remove an item from a list inside the for loop, after removing the i-th element, the next element in the list becomes the i-th current element.

    On the next repetition of the loop - when i is incremented by one - the current i + 1 item becomes the next item in the list, and thus you "lose" (at least) one item. Therefore, it is a bad idea to iterate through the list with the for command.

    However you may use many other methods available for collections - for instance Iterators - and your program will work fine.

        Iterator <String> it = string1List.iterator();
        
        while(it.hasNext())
            
        {
            if(it.next().equals("a")) it.remove();
        }
    

    Of course there is no need at all to use Lists to compare these two strings.