• Post Reply Bookmark Topic Watch Topic
  • New Topic

String Manipulations  RSS feed

 
Kevin Mills
Greenhorn
Posts: 3
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
So, I have a String, p, which I need to:

- trim off the beginning two character
- reverse it
- turn it into a char[]

In that order.

What I currently have is:



Which works, however it seems pretty unwieldy, so I'm wondering if there's a simpler (or more efficient) way to do it. Is what I have idiomatic Java?

If what I'm trying to do is not clear, I'll give an example. If p was the string "0x50B", like a typical representation of a hex number, I want a char array containing {'B', '0', '5'}, which again, my code does give me, but I'm just wondering if there's a better way to do it.
 
Jeanne Boyarsky
author & internet detective
Marshal
Posts: 37462
537
Eclipse IDE Java VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Kevin,
Welcome to CodeRanch!

I wouldn't use a StringBuilder there. You aren't saving any operations over a regular String. substring is called on the original String and returns a String so that is the same. Then the StringBuilder is created off of that String. reverse() doesn't create a new String because it is in StringBuilder. But then you immediately call toString() which does create a new String. I'd just write:


Let's suppose you had more operations and p is a very long String so the StringBuilder is worth it. Instead of:


You could write:


All I did was change the indentation. But it is a lot easier to see what is going on.
 
Kevin Mills
Greenhorn
Posts: 3
1
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Jeanne, thank you for the indentation tip about chaining method calls. I didn't realize you could do that - very helpful.

However, I don't think the String class has a reverse method. I checked its JavaDoc and it doesn't seem to have it listed. The fact that it didn't was precisely the reason I decided to use a StringBuilder.
 
Jeanne Boyarsky
author & internet detective
Marshal
Posts: 37462
537
Eclipse IDE Java VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Kevin Mills wrote: The fact that it didn't was precisely the reason I decided to use a StringBuilder.

You're right! I forgot about that because I was distracted by the chaining. Giving you a cow for successfully correcting a moderator. Speaking up is a good thing!

You can still use the indentation technique with your code at least.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!