Objective– Given two strings, find out if they are equal or not without using any built-in function (without using equals() function in java).
Example:
String x='tutorial' and String y='tutorial' are equal - true String x='tutorial' and String y='tutorial ' are equal - false String x='tutorial' and String y=' ' are equal – false
Approach:
- If any of the string is null, return false.
- If lengths of both strings are not matching, return false.
- Check if all the characters of both strings are matching, if not return false.
- If all the steps above got executed without returning false then return true.
Code:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class CompareStrings { | |
public static boolean compare(String x, String y){ | |
if(x==null || y==null){ | |
return false; | |
} | |
//compare lengths | |
if(x.length()!=y.length()) | |
return false; | |
//compare all characters | |
for (int i = 0; i <x.length() ; i++) { | |
if(x.charAt(i)!=y.charAt(i)) | |
return false; | |
} | |
//if here, means both strings are equal | |
return true; | |
} | |
public static void main(String[] args) { | |
String x = "tutorial"; | |
String y = "tutorial"; | |
System.out.println("String x='" + x + "' and String y='" + y + "' are equal?? –" + compare(x, y)); | |
x = "tutorial"; | |
y = "tutorial "; | |
System.out.println("String x='" + x + "' and String y='" + y + "' are equal?? –" + compare(x, y)); | |
x = "tutorial"; | |
y = " "; | |
System.out.println("String x='" + x + "' and String y='" + y + "' are equal?? –" + compare(x, y)); | |
} | |
} |
Output:
String x='tutorial' and String y='tutorial' are equal?? -true String x='tutorial' and String y='tutorial ' are equal?? -false String x='tutorial' and String y=' ' are equal?? -false