how to create an Encoder and Decoder for the Alphabetic substitution cipher (groovy)?
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)
精彩评论