+ 8

How to compare 2 strings?

10th Dec 2017, 4:46 PM
Tirtharaj D Roy
Tirtharaj D Roy - avatar
3 odpowiedzi
+ 8
String fooString1 = new String("foo"); String fooString2 = new String("foo"); // Evaluates to false fooString1 == fooString2; // Evaluates to true fooString1.equals(fooString2); // Evaluates to true, because Java uses the same object "bar" == "bar"; or String nullString1 = null; String nullString2 = null; // Evaluates to true nullString1 == nullString2; // Throws an Exception nullString1.equals(nullString2); == handles null strings fine, but calling .equals() from a null string will cause an exception:
10th Dec 2017, 4:57 PM
GAWEN STEASY
GAWEN STEASY - avatar
+ 3
1) String comparison using equals method 2) String comparison using equalsIgnoreCase method 3) String comparison using compareTo method 4) String comparison using comp public class StringComparisonExample {     public static void main(String args[]) {         String tv = "Bravia";         String television = "Bravia";         // String compare example using equals         if (tv.equals(television)) {             System.out.println("Both tv and television contains same letters and equal by equals method of String");         }         // String compare example in java using compareTo         if (tv.compareTo(television) == 0) {             System.out.println("Both tv and television are equal using compareTo method of String");         }         television = "BRAVIA";         // Java String comparison example using equalsIgnoreCase         if (tv.equalsIgnoreCase(television)){             System.out.println("tv and television are equal by equalsIgnoreCase method of String");         }         // String comparison example in java using CompareToIgnoreCase         if(tv.compareToIgnoreCase(television) == 0) {             System.out.println("tv and television are same by compareToIgnoreCase of String");         }         String sony = "Sony";         String samsung = "Samsung";         // lexicographical comparison of String in Java with ComapreTo         if (sony.compareTo(samsung) > 0) {             System.out.println("Sony comes after Samsung in lexicographical order");         } else if (sony.compareTo(samsung) <0) {             System.out.println("Sony comes before Samsung in lexicographical order");         }     } }
11th Dec 2017, 3:48 AM
Prabhat Thakur
Prabhat Thakur - avatar
+ 1
in c++,if there are 2 strings ,each of equal length, int temp=0; if(strlen(str1)==strlen(str2)) { for(int i=0;str[i]!="\n";++i) { if(str1[i]!=str2[i]) temp=-1; } } if(temp==0) cout<<"\nStrings are equal";
1st Jan 2018, 2:23 PM
Debarchan Tripathy
Debarchan Tripathy - avatar