0
Concepts
String functions: string length, character at index, uppercase conversion
Adding/Subtracting ASCII values of characters
Method creation
Constraints
Lowercase letters are converted to uppercase
All non-alpha characters are converted to space
Shifts outside of 0 through 25 are modded by 26; Languages that return negative values modulo of a negative number are converted to positive value
Use string “append” methods instead of creating new string objects when possible

C

# vi caesar.c
#include <stdio.h>
#include <string.h>

void caesarCipher(char *strText, int iShiftValue) {
  int i;
  char c;
  int iShift;
  char strCipherText[strlen(strText) + 1];

  iShift = iShiftValue % 26;
  if (iShift < 0) {
    iShift += 26;
  }

  i = 0;
  while (i < strlen(strText)) {
    c = toupper(strText[i]);
    if ( (c >= 'A') && (c <= 'Z')) {
      if ( (c + iShift) > 'Z') {
        strCipherText[i] = c + iShift - 26;
      } else {
        strCipherText[i] = c + iShift;
      }
    } else {
      strCipherText[i] = ' ';
    }
    i++;
  }
  strCipherText[i] = '';

  printf("%s\n", strCipherText);

}

int main(void) {
  caesarCipher("the quick brown fox jumps over the lazy dog", 3); 

  return 0;
}
# gcc caesar.c -o caesar
# ./caesar

C++

# vi caesar.cpp
#include <iostream>
#include <string>

using namespace std;

void caesarCipher(string strText, int iShiftValue) {
  int i;
  char c;
  int iShift;
  string strCipherText;

  strCipherText = "";

  iShift = iShiftValue % 26;
  if (iShift < 0) {
    iShift += 26;
  }

  i = 0;
  while (i < strText.size()) {
    c = toupper(strText.at(i));
    if ( (c >= 'A') && (c <= 'Z') ) {
      if ( (c + iShift) > 'Z') {
        strCipherText.push_back(c + iShift - 26);
      } else {
        strCipherText.push_back(c + iShift);
      }
    } else {
      strCipherText.push_back(' ');
    }
    i++;
  }

  cout << "CipherText: " << strCipherText << endl;
}

int main(void) {
  caesarCipher("the quick brown fox jumps over the lazy dog", 3);

  return 0;
}
# g++ caesar.cpp -o caesar
# ./caesar

Java

# vi Caesar.java
public class Caesar {

  public Caesar() {
    caesarCipher("the quick brown fox jumps over the lazy dog", 3);
  }

  private void caesarCipher(String strText, int iShiftValue) {
    int i;
    char c;
    int iShift;
    StringBuffer sb;
    String strCipherText;

    sb = new StringBuffer();
    strCipherText = "";

    iShift = iShiftValue % 26;
    if (iShift < 0) {
      iShift += 26;
    }

    i = 0;
    while (i < strText.length()) {
      c = Character.toUpperCase(strText.charAt(i));
      if ( (c >= 'A') && (c <= 'Z') ) {
        if ( (c + iShift) > 'Z') {
          sb.append((char) (c + iShift - 26));
        } else {
          sb.append((char) (c + iShift));
        }
      } else {
        sb.append(' ');
      }
      i++;
    }

    strCipherText = sb.toString();
    System.out.println(strCipherText);
  } 

  public static void main(String args[]) {
    new Caesar();
  }
}
# javac Caesar.java
# java Caesar

Ruby

#  vi caesar.rb
def caesarCipher(strText, iShiftValue)
  strCipherText = ""

  iShift = iShiftValue % 26
  if (iShift < 0)
    iShift += 26
  end

  i = 0
  while (i < strText.length)
    c = strText[i].chr.upcase
    if ( (c >= 'A') && (c <= 'Z') )
      if ( (c[0] + iShift) > 'Z'[0])
        strCipherText << (c[0] + iShift - 26)
      else
        strCipherText << (c[0] + iShift)
      end
    else
      strCipherText << ' '
    end

    i += 1
  end

  puts "#{strCipherText}"

end

caesarCipher("the quick brown fox jumps over the lazy dog", 3)
# ruby caesar.rb

Perl

# vi caesar.pl
sub caesarCipher {
  $strText = $_[0];
  $iShiftValue = $_[1];

  $strCipherText = "";
  @strTextArray = split(//, $strText);

  $iShift = $iShiftValue % 26;
  if ($iShift < 0) {
    $iShift += 26;
  }

  $i = 0;
  while ($i < length($strText)) {
    $c = uc($strTextArray[$i]);
    if ( ($c ge 'A') && ($c le 'Z') ) {
      if ( chr(ord($c) + $iShift) gt 'Z') {
        $strCipherText .= chr(ord($c) + $iShift - 26);
      } else {
        $strCipherText .= chr(ord($c) + $iShift);
      }
    } else {
      $strCipherText .= " ";
    }

    $i++;
  }

  print $strCipherText . "\n";
}

caesarCipher("the quick brown fox jumps over the lazy dog", 3);
# perl caesar.pl

Smalltalk (Squeak)

# squeak
| 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.
Highlight text in Transcript window, Alt-D (Do It)

Python

# vi caesar.py
def caesarCipher(strText, iShiftValue):
  strCipherText = ""

  iShift = iShiftValue % 26

  i = 0
  while (i < len(strText)):
    c = strText[i].upper()

    if ( (c >= 'A') & (c <= 'Z') ):
      if ( chr(ord(c) + iShift) > 'Z'):
        strCipherText += chr(ord(c) + iShift - 26)
      else:
        strCipherText += chr(ord(c) + iShift)
    else:
      strCipherText += ' ' 

    i += 1

  print strCipherText

caesarCipher("the quick brown fox jumps over the lazy dog", 3)
# python caesar.py

FORTRAN 77

# vi caesar.f
      program caesar
      call caesarCipher('the quick brown fox jumps over the lazy dog',
     +3)
      end

      subroutine caesarCipher(strText, iShiftValue)
      integer i, iShift, iShiftValue, iLen
      character strText*(*)
      character strCipherText(64)
      character c

      iShift = mod(iShiftValue, 26)
      if (iShift < 0) then
        iShift = iShift + 26
      end if

      i = 1
 10   if (i .LE. LEN(strText)) then
        c = strText(i:i)
        if ( (c .GE. 'a') .AND. (c .LE. 'z')) then
          c = CHAR(ICHAR(c) - (ICHAR('a') - ICHAR('A')))

        end if

        if ( (c .GE. 'A') .AND. (c .LE. 'Z') ) then
          if (ICHAR(c) + iShift .GT. ICHAR('Z')) then
            strCipherText(i) = CHAR(ICHAR(c) + iShift - 26)
          else
            strCipherText(i) = CHAR(ICHAR(c) + iShift)
          end if
        else
          strCipherText(i) = ' '
        end if

        i = i + 1

        goto 10
      end if

      print *, strCipherText

      return
      end
# gfortran caesar.f -o caesar
# ./caesar
Note:  Limit of 64 characters of cipher text;  may print garbage characters after cipher text

Scheme (MIT/GNU)

# vi caesar.scm
    (define strText "the quick brown fox jumps over the lazy dog")
    (define iShiftValue 3)
    (define strCipherText "")
    (define iShift (modulo iShiftValue 26))
    (define c "")
    (display iShift) (newline)
    (let loop ((i 0))
      (if (< i (string-length strText))
        (begin
          (set! c (char-upcase (string-ref strText i)))
          (if (char-alphabetic? c)
            (begin

              (if (> (+ (char-code c) iShift) (char-code #\Z))
                (begin
                  (set! strCipherText (string-append strCipherText (char->name (
                    make-char (- (+ (char-code c) iShift) 26) 0))))
                )
              )
              (if (not (> (+ (char-code c) iShift) (char-code #\Z)))
                (begin
                  (set! strCipherText (string-append strCipherText (char->name (
                    make-char (+ (char-code c) iShift)  0))))
                )
              )

            )
          ) 

          (if (not (char-alphabetic? c))
            (begin
              (set! strCipherText (string-append strCipherText " "))
            )
          )

          (loop (+ i 1))
        )
      )
    )
    (display strCipherText)(newline)
    (exit)
# scheme –load caesar.scm
Note:  Prints extra loading and closing output

Scala

# vi Caesar.scala
object Caesar {

  def caesarCipher(strText: String, iShiftValue: Int) = {
    var strCipherText = ""
    var sb = new StringBuilder("") 

    var iShift = iShiftValue % 26
    if (iShift < 0) {
      iShift += 26
    }

    var i = 0
    while (i < strText.length) {
      var c = strText.charAt(i).toUpperCase
      if ( (c >= 'A') && (c <= 'Z') ) {
        if ( (c + iShift) > 'Z') {
          sb.append((c + iShift - 26).toChar)
        } else {
          sb.append((c + iShift).toChar)

        }
      } else {
        sb.append(' ');
      }
      i += 1
    }

    println(sb.toString())
  }

  def main(args: Array[String]) {
    this.caesarCipher("the quick brown fox jumps over the lazy dog", 3)
  }
}
# scalac Caesar.scala
# scala Caesar

PHP

# vi caesar.php
<?php

  function caesarCipher($strText, $iShiftValue) {
    $strCipherText = "";

    $iShift = $iShiftValue % 26;
    if ($iShift < 0) {
      $iShift += 26;
    }

    $i = 0;
    while ($i < strlen($strText)) {
      $c = strtoupper($strText{$i}); 

      if ( ($c >= "A") && ($c <= 'Z')) {
        if ( (ord($c) + $iShift) > ord("Z") ) {
           $strCipherText .= chr(ord($c) + $iShift - 26);
        } else {
          $strCipherText .= chr(ord($c) + $iShift);
        }
      } else {
        $strCipherText .= " ";
      }

      $i++;
    }

    echo $strCipherText . "\n";
  }

  caesarCipher("the quick brown fox jumps over the lazy dog", 3);

?>
# php caesar.ph

bash script

# vi caesar.sh
#!/bin/bash

function caesarCipher {
  strText=$1
  iShiftValue=$2

  strCipherText=""
  iShift=$(( iShiftValue % 26 ))

  if [ $iShift -lt 0 ]; then
    iShift=$(( iShift + 26 ))
  fi

  i=0
  while [ $i -lt ${#strText} ]
  do
    c="$(echo ${strText:i:1} | tr '[a-z]' '[A-Z]')"
    if [[ $c =~ [A-Z] ]]; then
      n=$(printf "%d" "'$c")
      n=$(( n + iShift ))

      if [[ $n>$(printf "%d" "'Z") ]]; then
        n=$(( n - 26 ))
        str=$(printf \\$(printf '%03o' $n))
        strCipherText="${strCipherText}${str}" 

      else

        str=$(printf \\$(printf '%03o' $n))
        strCipherText="${strCipherText}${str}"
      fi
    else
      strCipherText="${strCipherText} "
    fi

    (( i++ ))
  done

  echo $strCipherText

}

caesarCipher "the quick brown fox jumps over the lazy dog" 3
# chmod u+x caesar.sh
# ./caesar.sh

Output

WKH TXLFN EURZQ IRA MXPSV RYHU WKH ODCB GRJ
Sumber

Poskan Komentar

 
Top