开发者

how to create an Encoder and Decoder for the Alphabetic substitution cipher (groovy)?

开发者 https://www.devze.com 2023-02-03 11:08 出处:网络
Basically i have to design and implement this on groovy ,开发者_JAVA技巧 this is to encode and decode a specific paragraph ?You can check out this

Basically i have to design and implement this on groovy ,开发者_JAVA技巧 this is to encode and decode a specific paragraph ?


You can check out this

http://groovy.codehaus.org/ExpandoMetaClass+-+Dynamic+Method+Names

which shows the typical use case for codecs.

Basically something like (from that link)

class HTMLCodec {
    static encode = { theTarget ->
        HtmlUtils.htmlEscape(theTarget.toString())
    }

    static decode = { theTarget ->
        HtmlUtils.htmlUnescape(theTarget.toString())
    }
}

you wont use the HtmlUtils, but the structure is the same.

EDIT -- here is an example on how to do the substitution. Note this can probably be more groovy, and it doesn't deal with punctuation, but it should help

def plainText = 'hello'
def solutionChars = new char[plainText.size()]
for (def i = 0; i < plainText.size(); i++){
        def currentChar = plainText.charAt(i)
        if (Character.isUpperCase(currentChar))
                solutionChars[i] = Character.toLowerCase(currentChar)
        else
                solutionChars[i] = Character.toUpperCase(currentChar)

}

def cipherText = new String(solutionChars)
println(solutionChars)

EDIT -- here is a solution that is a bit more groovy

def plainText = 'hello'
def cipherText = ""
plainText.each {c ->
    if (Character.isUpperCase((Character)c))
        cipherText += c.toLowerCase()
    else
        cipherText += c.toUpperCase()
}

println(cipherText)
0

精彩评论

暂无评论...
验证码 换一张
取 消