Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * Stores a string of text and provides a method for returning a version of the
- * text with each character shifted by a specified number of characters to the
- * right in the alphabet.
- *
- * @file StringShifter.java
- * @author oz <oz@freqlabs.com>
- * @date 2013-11-16
- */
- /*
- Copyright 2013 Freq Labs
- Licensed under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License.
- You may obtain a copy of the License at
- http://www.apache.org/licenses/LICENSE-2.0
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
- */
- public class StringShifter
- {
- private String text;
- /**
- * Performs bounds checking on the specified number.
- *
- * @param amount the number to bounds check.
- * @return <code>true</code> if amount is between 1 and 25,
- * inclusive; <code>false</code> otherwise.
- */
- private boolean isValidShift(int amount)
- {
- return 0 < amount && amount < 26;
- }
- /**
- * Shift a character n to the right in the alphabet, wrapping back to the
- * beginning of the alphabet if the result exceeds base + 25.
- *
- * @param c the character to shift.
- * @param n the amount of the shift.
- * @param base the character to wrap back to.
- * @return the shifted and wrapped value of c.
- */
- private char shiftFromBase(char c, int n, char base)
- {
- return (char)(((int)c + n - (int)base) % 26 + (int)base);
- }
- /**
- * Constructor for initializing the value of the text field.
- *
- * @param initialText the initial value to assign the text field.
- */
- public StringShifter(String initialText)
- {
- text = initialText;
- }
- /**
- * Return a String with each character in the text field shifted to the
- * right in the alphabet by the specified amount. If the shift amount is out
- * of range, the original text is returned.
- * Only alphabetical characters are shifted, everything else is unmodified.
- *
- * @param n the number of characters to shift the text.
- * @return the shifted text if n is in bounds; the original text
- * otherwise.
- */
- public String shift(int n)
- {
- String result_text;
- if ( isValidShift(n) )
- {
- result_text = "";
- for (char c : text.toCharArray())
- {
- if ('A' <= c && c <= 'Z')
- result_text += shiftFromBase(c, n, 'A');
- else if ('a' <= c && c <= 'z')
- result_text += shiftFromBase(c, n, 'a');
- else
- result_text += c;
- }
- }
- else
- {
- result_text = text;
- }
- return result_text;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement