Search code examples
groovy

How to compare 2 strings in groovy?


There are 2 strings in groovy files :1) 01xx01xx01 and 2) 0101010111 and I want to compare only non-x elements. eg only compare 010101 with 010111 (ignore "x"). The following scripts were created by me (written in groovy). It works but needs many lines of code. Are there any other ways to do it?

a="01xx01xx01"
b="0101010111"
def compareStrings(String a,String b){
    i=0
    while (i<a.length){
        if (a[i] =="X" || b[i]=="X"){
            i+=1}
        else if (a[i]!=b[i]){
            return "Not Similar"}
        else{
            i+=1}
    return "Similar"
    }
}
def result = compareStrings(str1,str2)  
println(result) 

Solution

  • There are 2 strings in groovy files :1) 01xx01xx01 and 2) 0101010111 and I want to compare only non-x elements. eg only compare 010101 and 010111.

    working Groovy code below

    println "str match"
    
    def str1 = '01xx01xx01'
    def str2 = '0101010111'
    def str3 = '01xx01xx01'
    
    def sameStringsIgnoreX(str1,str2) {
        def temp1 = str1.replaceAll('x','')
        def temp2 = str2.replaceAll('x','')
        temp1 == temp2
    
    }
    
    def sameStrings = sameStringsIgnoreX(str1,str2)
    println(sameStrings)
    
    sameStrings = sameStringsIgnoreX(str1,str3)
    println(sameStrings)
    

    output

    str match
    false
    true