Reputation: 21
I'm trying to rearrange the characters of a string so that the first character comes after the next two characters following after it, i.e. if the string is "abc", the rearrangement would be "bca". This process would then repeat itself over larger strings for each grouping of three characters, i.e. if the string is "tcagdo", the rearrangement would be "catdog", and so on.
This is the code that I have so far:
public String oneTwo(String str) {
String rep = str;
if(str.length() < 3){
return "";
}
for(int j = 0;j < str.length();j = j+3){
for(int i = 0;i < str.length();i = i + 3){
rep =str.substring(i+1,i+3) + str.substring(i,i+1);
}
return rep;
}
return rep;
}
There's a series of tests that it runs through, and it works for some of them, but not for all of them. I just need help getting pointed in the right direction.
Upvotes: 0
Views: 1057
Reputation: 6017
public static void main(String[] args) {
System.out.println(oneTwo("tcagdo"));
}
private static String oneTwo(String str) {
if (str.length() < 3) return "";
char[] res = str.toCharArray();
for (int j = 0; j < res.length; j += 3){
if (j + 3 > res.length) {
break;
} else {
char temp = res[j];
res[j] = res[j + 1];
res[j + 1] = res[j + 2];
res[j + 2] = temp;
}
}
return String.valueOf(res);
}
Just a simple 3-way swap using a temp
variable with an additional check if the length
is not divisible by 3.
char[]
array is better for swapping elements because Strings
are immutable in Java
.
Upvotes: 0
Reputation: 521063
Not to spoil your assignment, but regex replacement offers a very concise way to do this:
String input = "tcagdo";
String output = input.replaceAll("(.)(..)", "$2$1");
System.out.println(output);
The regex pattern (.)(..)
matches three characters at a time, capturing the first and last two in separate capture groups. The replacement then splices together the groups using the ordering you want.
Upvotes: 6