| Author |
Return Two Rightmost Characters
|
Steve Dyke
Ranch Hand
Joined: Nov 16, 2004
Posts: 1260
|
|
|
I need some help with code that will return the two rightmost characters of a string. And how to handle if string is "".
|
 |
Jesper de Jong
Java Cowboy
Bartender
Joined: Aug 16, 2005
Posts: 12950
|
|
Have a look at the Javadoc API documentation of class String (a link to the documentation is in my signature below). It contains a lot of useful methods to manipulate strings. There are for example methods to return the number of characters in a string and to get a substring out of a string. With those two methods it's easy to solve your problem. Experiment with Java yourself, that way you'll learn it much quicker then when someone just gives you the answer.
|
Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 7 API documentation
Scala Notes - My blog about Scala
|
 |
Steve Dyke
Ranch Hand
Joined: Nov 16, 2004
Posts: 1260
|
|
My challenge is this: My String could be 854411-401(001),854411-403(001), or 854411-401(001),854411-403(001,002, I need to check and see if the last two characters are ")," From the API functions I don't see an obvious solution. Thats why I have aquired the assistance of the experts.
|
 |
Paul Clapham
Bartender
Joined: Oct 14, 2005
Posts: 16487
|
|
Originally posted by Steve Dyke: I need to check and see if the last two characters are "),".
So you want to see if the string ends with "),"? And you didn't see any method in the String API for that?
|
 |
Steve Dyke
Ranch Hand
Joined: Nov 16, 2004
Posts: 1260
|
|
After some more digging I came up with: myString = myString.substring(myString.length()-2) It seems to work fine. I am used to developing in another language which had a function Right(myString,2)
|
 |
Paul Clapham
Bartender
Joined: Oct 14, 2005
Posts: 16487
|
|
Yes, that will give you the last two characters of the string, or throw an exception if the string has zero characters or one character. But if you just want to know if the string ends with ")," thenwill do fine. It behaves nicely on empty strings, too. And I used to develop in that other language too. Not any more. [ December 10, 2007: Message edited by: Paul Clapham ]
|
 |
 |
|
|
subject: Return Two Rightmost Characters
|
|
|