Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.*;
- /**
- * Created by Indrid on 11/15/2015.
- */
- public class E240 {
- public static void main(String[] args) {
- Scanner inputScanner = new Scanner(System.in);
- System.out.print("Input the string\n>> ");
- System.out.println(stringParser(inputScanner.nextLine()));
- }
- // Takes a sentence string and returns the scrambled string
- static String stringParser(String input) {
- StringTokenizer st = new StringTokenizer(input, " ");
- String finalOutput = ""; // Final shuffled sentence
- while (st.hasMoreTokens()) {
- String word = st.nextToken();
- char wordBuffer[] = new char[word.length()]; // Temp storage as word is shuffled
- String stringToBeShuffled = ""; // String excluding special characters to be shuffled
- // Stores non-alpha characters in their corresponding places into the wordBuffer char array
- // Stores alpha characters the "stringToBeBuffer" string
- for (int i = 0; i < word.length(); i++) {
- wordBuffer[i] = ' ';
- if ((word.charAt(i) >= 'a' && word.charAt(i) <= 'z') || (word.charAt(i) >= 'A' && word.charAt(i) <= 'Z')) {
- stringToBeShuffled += word.charAt(i);
- } else {
- wordBuffer[i] = word.charAt(i);
- }
- }
- // Places the scrambled alpha characters back into the open spaces on the
- String tempStr = wordScrambler(stringToBeShuffled);
- for (int i = 0, j = 0; i < word.length(); i++) {
- if (wordBuffer[i] == ' ') {
- wordBuffer[i] = tempStr.charAt(j);
- j++;
- }
- }
- finalOutput += String.valueOf(wordBuffer) + " ";
- }
- return finalOutput;
- }
- static String wordScrambler(String input) { // The person reading this code is lucky I didn't scramble the function name
- String output = "";
- int strLen = input.length();
- if (strLen > 3) {
- output += input.charAt(0);
- output += shuffleString(input.substring(1, strLen - 1));
- output += input.charAt(strLen - 1);
- } else {
- output = input;
- }
- return output;
- }
- // Shuffles the inputted string excluding the first and last characters. Guarantees a different word for words with length > 3
- static String shuffleString(String string) {
- String shuffled;
- do {
- shuffled = "";
- List<String> letters = Arrays.asList(string.split(""));
- Collections.shuffle(letters);
- for (String letter : letters) {
- shuffled += letter;
- }
- } while (shuffled.equals(string) && shuffled.length() > 1
- && shuffled.charAt(0) != shuffled.charAt(1)); // Only get's checked if above isn't true
- return shuffled;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment