Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Groovy - How to compare the string?

Tags:

groovy

how to compare the string which is passed as a parameter

the following method is not working.

 String str = "saveMe"   compareString(str)   def compareString(String str){     def str2 = "saveMe"     if(str2==${str}){       println "same"     }else{       println "not same"     }  }     

also tried

 String str = "India"   compareString(str)   def compareString(String str){    def str2 = "india"    if( str2 == str ) {      println "same"    }else{      println "not same"    }  }     
like image 523
user1602802 Avatar asked Aug 16 '12 09:08

user1602802


People also ask

How do I compare values in Groovy?

Groovy - compareTo() The compareTo method is to use compare one number against another. This is useful if you want to compare the value of numbers.

What is == in Groovy?

In Groovy == translates to a. compareTo(b)==0, if they are Comparable, and a. equals(b) otherwise.

How do I compare two objects in Groovy?

In Groovy we use the == operator to see if two objects are the same, in Java we would use the equals() method for this. To test if two variables are referring to the same object instance in Groovy we use the is() method. The !=


2 Answers

This should be an answer

str2.equals( str )

If you want to ignore case

str2.equalsIgnoreCase( str )

like image 196
ojblass Avatar answered Oct 09 '22 10:10

ojblass


This line:

if(str2==${str}){ 

Should be:

if( str2 == str ) { 

The ${ and } will give you a parse error, as they should only be used inside Groovy Strings for templating

like image 42
tim_yates Avatar answered Oct 09 '22 08:10

tim_yates