String
Easy
Given a non-empty string of lowercase letters and a non-negative integer
representing a key, write a function that returns a new string obtained by
shifting every letter in the input string by k positions in the alphabet,
where k is the key.
Note that letters should "wrap" around the alphabet; in other words, the
letter z
shifted by one returns the letter a
.
Most languages have built-in functions that give you the Unicode value of a character as well as the character corresponding to a Unicode value. Consider using such functions to determine which letters the input string's letters should be mapped to.
Try creating your own mapping of letters to codes. In other words, try associating each letter in the alphabet with a specific number - its position in the alphabet, for instance - and using that to determine which letters the input string's letters should be mapped to.
How do you handle cases where a letter gets shifted to a position that requires wrapping around the alphabet? What about cases where the key is very large and causes multiple wrappings around the alphabet? The modulo operator should be your friend here.
是一種最簡單且最廣為人知的加密技術。凱撒密碼是一種替換加密技術,明文中的所有字母都在字母表上向後(或向前)按照一個固定數目進行偏移後被替換成密文。例如,當偏移量是3的時候,所有的字母A將被替換成D,B變成E,以此類推。
這個加密方法是以羅馬共和時期凱撒的名字命名的,據稱當年凱撒曾用此方法與其將軍們進行聯繫。
凱撒密碼通常被作為其他更複雜的加密方法中的一個步驟,但是和所有的利用字母表進行替換的加密技術一樣,凱撒密碼非常容易被破解,而且在實際應用中也無法保證通信安全。
String.prototype.charCodeAt()
返回一個介於 0 和 65535 之間的整數,表示給定索引處的 UTF-16 代碼單元。
用法:
補充:UTF-16
Unicode 是國際標準字符集,它將世界各種語言的每個字符定義一個唯一的編碼,以滿足跨語言、跨平臺的文本信息轉換。
UTF-16 是一種變長字符編碼, 這種編碼方式比較特殊, 它將字符編碼成 2 字節 或者 4 字節。
英文字母 a-z 是 97-122
數字 0-9 是 48-57
String.fromCharCode()
返回由指定的 UTF-16 代碼單元序列創建的字串。