Home > Net >  How to check that 2 strings are actually equal and have same characters? Even with spacing or lowerc
How to check that 2 strings are actually equal and have same characters? Even with spacing or lowerc

Time:04-04

Can anyone help me? I am trying to compare 2 strings if its equal or not (without considering spaces and cases)

Examples:

"Abc1", "Abc1 " -> true (with spacing at the end)

"Abc1", "abc1" -> true (with lowercase)

"Abc1", " Abc1 " -> true (with spacing at the beginning and at the end of the string)

"Abc1", " abc1 " -> true (with lowercase and spacing at the beginning and at the end of the string)

It should have the same order, and if its not the same order, it will returns false

"Abc1", "Ac1b " -> false

I already tried this code, but it didnt give me the result I was looking for

public static boolean sameChars(String firstStr, String secondStr) {
    char[] first = firstStr.toCharArray();
    char[] second = secondStr.toCharArray();
    Arrays.sort(first);
    Arrays.sort(second);
    return Arrays.equals(first, second);
}

CodePudding user response:

If your intention is only to compare then there's no need to convert the string to a char array.

To ignore spaces at the beginning and end of the strings use trim()

Ex:

firstStr.trim()

To compare ignoring cases use equalsIgnoreCase()

Ex:

firstStr.equalsIgnoreCase(secondStr)

If you want to ignore all spaces in the string, even if it is within the string, you will have to use replace(char oldchar, char newchar) rather than trim().

Ex:

firstStr.replace(" ","")

Assuming you only want to ignore the spaces in the beginning and end, to compare do: firstStr.trim().equalsIgnoreCase(secondStr.trim())

If you want to ignore all spaces:

firstStr.replace(" ", "").equalsIgnoreCase(secondStr.replace(" ", "")

CodePudding user response:

You don't need to convert your Strings to Character. Here you have to use this java inbuilt method trim() and equalsIgnoreCase().

public static boolean sameChars(String firstStr, String secondStr) {
    boolean checkString = firstStr.trim().equalsIgnoreCase(secondStr.trim());
    return checkString;
}   
  • Related