Reversing of string

I have a string as Apple->Ball->Cat->Dog and want to reverse it as Dog->Cat->Ball->Apple. It can be done by splitting the string at every '->' and then adding each element is an array and then reverse the array and then add the arrows. But is there any faster way to do so? What would be the quickest possible way of reversing it using java?

Answers


Do not use tokenization. You may try StringBuffer reverse method:

String input = "A->B->C->D";
input = input.replace("->", "-");
input = new StringBuffer(input).reverse().toString();
input = input.replace("-", "->");
System.out.println(input);

This will hold the -> in the right order:

input: "A->B->C->D"
output: "D->C->B->A"

Good Luck;

[EDIT]:

Ok, at first you didn't mention that the your String may contains other than single characters. So the above answer cannot maintain your needs. But if you have unique names in your string you may use this way by substituting every name with a single character and it works. But I'm not sure it would be better than your own solution(Tokenize to an array and reverse the array).


For better performance use this. I am assuming that your A,B,C,D are literally characters then you can take advantage of the position in string. Just convert your string into StringBuilder and do the following.

StringBuilder sb = new StringBuilder("A->B->C->D");
int len = sb.length();
for (int i = 0; i < len / 2; i+=3) {
  int j = len - (i + 1);
  char temp = sb.charAt(i);
  sb.setCharAt(i, sb.charAt(j));
  sb.setCharAt(j, temp);
}
System.out.print(sb.toString());

If it is only one character after each arrow, it might be faster to use replaceAll("->", "") so that you get rid of all the arrows, reverse the String you get (if you didn't remove the -> you'd obviously reverse the arrows aswell), and then add your arrows after each character. That being said it probably doesn't change much on the scope of performance, and it doesn't work with strings longer than 1 character, so I would just stick to your original plan.


Need Your Help

Ivy: how do I remove transitive dependencies?

ant dependencies ivy

I'm using Ivy to manage the dependencies on my project.

Beaglebone black (BBB) rev C 3.8.13-38-ARCH SPI doesn't work, Inappropriate ioctl for device

beagleboneblack spi archlinux-arm

I have troubles with enabling SPI on BBB, ofc followed tutorial from the hipstercircuits.com.