如何为字母替换密码(groovy)创建编码器和解码器?

发布于 2024-10-10 17:12:01 字数 44 浏览 4 评论 0原文

基本上我必须在groovy上设计和实现这个,这是为了编码和解码特定的段落?

Basically i have to design and implement this on groovy , this is to encode and decode a specific paragraph ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

傲世九天 2024-10-17 17:12:01

您可以查看此

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

显示了编解码器的典型用例。

基本上类似(来自该链接)

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

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

您不会使用 HtmlUtils,但结构是相同的。

编辑 - 这是一个如何进行替换的示例。请注意,这可能更常规,并且它不处理标点符号,但它应该有助于

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)

编辑 - 这是一个更常规的解决方案

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

println(cipherText)

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)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文