Groovy - ¿Cómo comparar la cuerda?


Cómo comparar la cadena que se pasa como parámetro

El siguiente método no funciona.

 String str = "saveMe"

 compareString(str)

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

También se intentó

 String str = "India"

 compareString(str)

 def compareString(String str){
   def str2 = "india"
   if( str2 == str ) {
     println "same"
   }else{
     println "not same"
   }
 }    
 47
Author: amarillion, 2012-08-16

6 answers

Esta línea:

if(str2==${str}){

Debe ser:

if( str2 == str ) {

Los ${ y } le darán un error de análisis, ya que solo deben usarse dentro de cadenas Groovy para crear plantillas

 45
Author: tim_yates,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-08-16 09:33:53

Esto debería ser una respuesta

Str2.equalsIgnoreCase (str)

 77
Author: ojblass,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-05-08 18:57:03

Si no desea verificar en mayúsculas o minúsculas, puede usar el siguiente método.

String str = "India" 
compareString(str) 

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

Así que ahora, si cambias str a "iNdIa", seguirá funcionando, por lo que disminuirás la posibilidad de que hagas un error tipográfico.

 6
Author: Dieterg,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-08-16 09:45:35

El camino más corto (imprimirá "no es lo mismo" porque la comparación de cadenas distingue entre mayúsculas y minúsculas):

def compareString = {
   it == "india" ? "same" : "not same"
}    

compareString("India")
 2
Author: Simek,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-01-21 08:42:10

Utilice la variable def, cuando quiera comparar cualquier cadena. Utilice el siguiente código para ese tipo de comparación.

Def variable name = null

La consulta SQL le dará algún retorno. Use la función con el tipo de retorno def.

Def functionname (def variablename) {

Devuelve el nombre de la variable

}

If ("variable variable name" = = "true") {

}

 -4
Author: Deepanshu Jain,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-03-03 12:50:01

En Groovy, null == null obtiene un true. En tiempo de ejecución, no sabrás lo que pasó. En Java, == es comparar dos referencias.

Esto es una causa de gran confusión en la programación básica, si es seguro usar equals. En tiempo de ejecución, un null.igual dará una excepción. Tienes la oportunidad de saber qué salió mal.

Especialmente, obtienes dos valores de claves que no existen en mapas, == las hace iguales.

 -5
Author: user4313287,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-03-11 10:02:43