Groovy - How to compare the string?

If you don't want to check on upper or lowercases you can use the following method.

String str = "India" 
compareString(str) 

def compareString(String str){ 
  def str2 = "india" 
  if( str2.toUpperCase() == str.toUpperCase() ) { 
    println "same" 
  }else{ 
    println "not same" 
  } 
}

So now if you change str to "iNdIa" it'll still work, so you lower the chance that you make a typo.


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


This should be an answer

str2.equals( str )

If you want to ignore case

str2.equalsIgnoreCase( str )

Tags:

Groovy