next up previous
Next: Example of for loop: Up: Unit 06 Previous: Examples of for loops

Example of for loop: encoding a string

Write a public static method that takes as parameters a string and an integer d, and returns the encoding of the string with the integer. The encoding is obtained by substituting each character c in the string with the character that has the code equal to the code of c incremented by d.

Example: "ciao" with d= 3 becomes "fldr"

public static String encode(String s, int d) {

  String resStr;
  char c;
  int ci;

  resStr = "";
  for (int i = 0; i < s.length(); i++) {
    c = s.charAt(i);
    ci = (int)c;
    ci += d;
    c = (char)ci;
    resStr = resStr + c;
   }
   return resStr;
}


next up previous
Next: Example of for loop: Up: Unit 06 Previous: Examples of for loops