Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Return Two Rightmost Characters

 
Steve Dyke
Ranch Hand
Posts: 1619
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 15214
36
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Steve Dyke
Ranch Hand
Posts: 1619
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Sheriff
Pie
Posts: 20945
31
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 1619
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Sheriff
Pie
Posts: 20945
31
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic