Created
July 8, 2013 07:35
-
-
Save sinanduman/5946898 to your computer and use it in GitHub Desktop.
Change the middle word with last word.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package learn; | |
public class MiddleWordSwap { | |
public static void main(String[] args) { | |
char[] str = "Java is nice but Scala is even better :)".toCharArray(); | |
char[] goal = "Java is nice but :) is even better Scala".toCharArray(); | |
System.out.println("Original: '" + new String(str) + "'"); | |
str = rearrange(str); | |
boolean success = new String(str).equals(new String(goal)); | |
System.out.println("Re-arranged: '" + new String(str) | |
+ "'\n\nOperation " + (success ? "succeeded." : "failed!")); | |
} | |
private static char[] rearrange(char[] str) { | |
String[] strArray = (new String(str)).split(" "); | |
int sizeArray = strArray.length; | |
String temp = strArray[sizeArray / 2]; | |
strArray[sizeArray / 2] = strArray[sizeArray - 1]; | |
strArray[sizeArray - 1] = temp; | |
StringBuilder tempResult= new StringBuilder(""); | |
for (String tmp : strArray) { | |
tempResult.append(tmp + " "); | |
} | |
str = tempResult.toString().trim().toCharArray(); | |
return str; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment