Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package edu.wit.cs.comp1050;
- import java.util.ArrayList;
- public class Shifter {
- /**
- * Number of letters in the English alphabet
- */
- public static final int NUM_LETTERS = ('z' - 'a') + 1;
- private String s;
- /**
- * Initializes the shifter
- *
- * @param s encrypted string
- */
- public Shifter(String s) {
- this.s = s;
- }
- /**
- * Returns the result of shifting by a supplied amount
- *
- * @param n number of places to shift
- * @return shifted string
- */
- public String shift(int n) {
- StringBuilder newString = new StringBuilder();
- char[] letters = s.toCharArray();
- if (s.isEmpty()) {
- return "";
- }
- else if (s == " ") {
- return " ";
- }
- if (n > 26 || n < -26) {
- n = n % 26;
- }
- for (int i = 0; i < letters.length; i++) {
- if (letters[i] >= 'a' && letters[i] <= 'z') {
- if (letters[i] + n < 'a') {
- letters[i] = (char) ((letters[i] + n) + 26);
- } else if (letters[i] + n > 'z') {
- letters[i] = (char) ((letters[i] + n) - 26);
- }
- else {
- letters[i] = (char) (letters[i] + n);
- }
- }
- if (letters[i] >= 'A' && letters[i] <= 'Z') {
- if (letters[i] + n < 'A') {
- letters[i] = (char) ((letters[i] + n) + 26);
- } else if (letters[i] + n > 'Z') {
- letters[i] = (char) ((letters[i] + n) - 26);
- } else {
- letters[i] = ((char) (letters[i] + n));
- }
- }
- }
- for (int i = 0; i < letters.length; i++) {
- newString.append(letters[i]);
- }
- return newString.toString();
- }
- /**
- * Finds all shifts that contain the supplied substring
- *
- * @param sub substring to find
- * @return array of shifts (0-25) that contain the substring (in order)
- */
- public int[] findShift(String sub) {
- String method;
- ArrayList<Integer> shifts = new ArrayList<>();
- int count = 0;
- for (int i = 0; i <= 25; i++) {
- method = shift(count);
- if (method.contains(sub)) {
- shifts.add(i);
- }
- count++;
- }
- int[] numShifts = new int[shifts.size()];
- for (int i = 0; i < numShifts.length; i++) {
- numShifts[i] = shifts.get(i);
- }
- return numShifts;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement