Smalltalk 创建凯撒密码方法

Smalltalk 创建凯撒密码方法,smalltalk,pharo,caesar-cipher,Smalltalk,Pharo,Caesar Cipher,所以我需要在smalltalk中获得Caesar密码,创建一个方法并使用它,以便对其进行以下测试 |aString| aString:=Caesar new encrypt: 'CAESAR'. Transcript show: aString. 我已经安排好上课了。但是我需要制定一个方法 我发现了这一点,但我如何才能从中找到一个方法,这样我就可以在操场上使用上面的所有代码 | i c strCipherText strText iShiftValue iShift | strText :=

所以我需要在smalltalk中获得Caesar密码,创建一个方法并使用它,以便对其进行以下测试

|aString|
aString:=Caesar new encrypt: 'CAESAR'.
Transcript show: aString.
我已经安排好上课了。但是我需要制定一个方法

我发现了这一点,但我如何才能从中找到一个方法,这样我就可以在操场上使用上面的所有代码

| i c strCipherText strText iShiftValue iShift |

strText := 'the quick brown fox jumps over the lazy dog'.
iShiftValue := 3.

strCipherText := ''.
iShift := iShiftValue \\ 26.

i := 1.
[ i <= (strText size) ]
whileTrue: [
  c := (strText at: i) asUppercase.

  ( ( c >= $A) & ( c <= $Z ) )
  ifTrue: [

    ((c asciiValue) + iShift > $Z asciiValue)
    ifTrue: [
      strCipherText := strCipherText, (((c asciiValue) + iShift - 26)
                      asCharacter asString).
    ]
    ifFalse: [
      strCipherText := strCipherText, (((c asciiValue) + iShift)
                      asCharacter asString).
    ].

  ]
  ifFalse: [
    strCipherText := strCipherText, ' '.
  ].

  i := i + 1.
].

Transcript show: strCipherText.
Transcript cr.
| i c stripherText strText iShiftValue iShift|
strText:=“敏捷的棕色狐狸跳过了懒惰的狗”。
iShiftValue:=3。
stripherText:=''。
iShift:=iShiftValue\\26。
i:=1。
[i=$A)和(c$Z)
如果是:[
striphertext:=striphertext,((c ascivalue)+iShift-26)
asCharacter asString)。
]
如果是:[
striphertext:=striphertext,((c ascivalue)+iShift)
asCharacter asString)。
].
]
如果是:[
stripherText:=stripherText“”。
].
i:=i+1。
].
成绩单显示:striphertext。
转录本。
所以,为了让事情变得清楚,我需要使用凯撒密码制作一个方法,并在开始时使用“aString”代码,并用它进行测试。我上面有这段代码,但里面已经有文本,无法放入方法中


任何帮助都将不胜感激

正如Max在评论中所说,上面的代码可以放在一个方法中。唯一缺少的部分是带有选择器和形式参数的第一行:

caesarCipherOf: strText
  <insert the code here>
其中
64=$A码点-1
,是
$A
和任何给定大写字符
c
之间的偏移量。还请注意,我已将
ascivalue
替换为
codePoint

通过这两个观察,该方法可以重新编写为

    caesarCipherOf: aString
      ^aString collect: [:c |
        c isLetter
          ifTrue: [(c asUppercase codePoint - 64 + 3 \\ 26 + 64) asCharacter]
          ifFalse: [$ ]]
这不仅更短,而且效率更高,因为它避免了在每个字符处创建两个
字符串的新实例。具体来说,任何形式的表达

string := string , <character> asString
string:=字符串,关联字符串

创建两个
字符串
:一个作为发送
#asString
的结果,另一个作为发送连接消息
#,
的结果。相反,
#collect:
只创建一个实例,即方法返回的实例。

当然可以将其放入方法中。只需用方法参数替换strText
。例如:该方法可能被称为
#myCaesorCodeOf:
,并使用一个名为
aString
@MaxLeske的参数。我对使用pharo和Smalltalk还不太熟悉,所以我真的不知道该怎么做。
string := string , <character> asString