Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get integer difference between string just like strcmp

I just need a function that will, for two given strings, return negative, positive or zero value. In C, strcmp is used:

char* a = "Hello";
char* b = "Aargh";

strcmp(a, b);  //-1
strcmp(a, a);  //0
strcmp(b, a);  //1

Does Java have any easy intuitive way to do it, or do I have to use the Comparator interface?

like image 614
Tomáš Zato - Reinstate Monica Avatar asked May 29 '14 13:05

Tomáš Zato - Reinstate Monica


2 Answers

Does Java have any easy intuitive way to do it?

Yes, it does: java.lang.String implements Comparable<String> interface, with compareTo function:

int comparisonResult = a.compareTo(b);

There is also a case-insensitive version:

int comparisonResult = a.compareToIgnoreCase(b);
like image 85
Sergey Kalinichenko Avatar answered Oct 05 '22 08:10

Sergey Kalinichenko


The String.compareTo method is the way to go in Java.

How to use it :

import java.lang.*;

public class StringDemo {

  public static void main(String[] args) {

    String str1 = "tutorials", str2 = "point";

    // comparing str1 and str2
    int retval = str1.compareTo(str2);

    // prints the return value of the comparison
    if (retval < 0) {
       System.out.println("str1 is less than str2");
    }

    else if (retval == 0) {
       System.out.println("str1 is equal to str2");
    }

    else {
       System.out.println("str1 is greater than str2");
    }
  }
}

Output :

str1 is less than str2

Example taken from : http://www.tutorialspoint.com/java/lang/string_compareto.htm

like image 35
slaadvak Avatar answered Oct 05 '22 07:10

slaadvak