简体   繁体   中英

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

基本上我必须在groovy上设计和实现,这是对特定段落进行编码和解码吗?

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM