File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Beginning Java and the fly likes Return Two Rightmost Characters Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Return Two Rightmost Characters" Watch "Return Two Rightmost Characters" New topic
Author

Return Two Rightmost Characters

Steve Dyke
Ranch Hand

Joined: Nov 16, 2004
Posts: 1413
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
Saloon Keeper

Joined: Aug 16, 2005
Posts: 14107
    
  16

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: 1413
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: 18541
    
    8

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: 1413
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: 18541
    
    8

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 ]
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Return Two Rightmost Characters