Reputation: 9827
I have a Java String "test/this/string"
that I want to reverse to "string/this/test"
using a regular expression or the most efficient Java algorithm. The way I know is to use the split method, loop over the array and rebuild the string manually. The number of "/" can vary and doesn't occur a fixed number of times. Any ideas?
Upvotes: 2
Views: 3380
Reputation: 425003
This can be done in one line using regex:
String reversed = str.replaceAll("(.*?)(/.*?)?(/.*?)?(/.*?)?(/.*?)?(/.*?)?(/.*?)?(/.*?)?(/.*?)?", "$9$8$7$6$5$4$3$2$1").replaceAll("^/", "");;
The way this works is the regex matches the whole string and captures the parts as separate groups, then the replacement string has back referenced to those captured groups to put them back in the reverse order.
This works for 1-9 parts.
Upvotes: 1
Reputation: 55609
Here's my take:
String input = "test/this/string";
List<String> list = Arrays.asList(input.split("(?=/)|(?<=/)"));
Collections.reverse(list);
StringBuilder sb = new StringBuilder();
for (String s: list)
sb.append(s);
System.out.println(sb.toString());
(?<=/)
is a zero-length matching regex that matches if the previous character is a /
.
(?=/)
is a zero-length matching regex that matches if the next character is a /
.
So (?=/)|(?<=/)
matches right before and after each /
, thus the split
splits the string into "test", "/", "this", "/", "string"
.
Test.
Upvotes: 1
Reputation: 129507
Here's an idea, using lastIndexOf()
:
String str = "string/this/test";
StringBuilder rev = new StringBuilder(str.length());
int start = str.lastIndexOf('/'), end = str.length();
while (start >= 0) {
rev.append(str.substring(start + 1, end));
rev.append('/');
end = start;
start = str.lastIndexOf('/', start - 1);
}
rev.append(str.substring(0, end));
System.out.println(rev);
test/this/string
Upvotes: 1