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

Time:01-22

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

}

CodePudding user response:

You can try below solution. As you mentioned word spacing and capitalization do not matter

1.remove capitalization - using toLowercase() 2.for word spacing - remove all word spacing using removeAll() with regex pattern "\\s " so it removes all spaces. 3. check both strings now.

public class StringChecker {
    public static void main(String[] args) {
        System.out.println(checkString("This is a first string", "this is   a first string"));
    }


    public static boolean checkString(String string1, String string2){
        String processedStr1 = string1.toLowerCase().replaceAll("\\s ", "");
        String processedStr2 = string2.toLowerCase().replaceAll("\\s ", "");
        System.out.println(" s1 : "   processedStr1);
        System.out.println(" s2 : "   processedStr2);
        return processedStr1.equals(processedStr2);
    }
}
  •  Tags:  
  • Related