| Author |
substring to just get the last character
|
Candy Bortniker
Ranch Hand
Joined: Mar 17, 2003
Posts: 123
|
|
|
I have a variable called "last" that only contains numbers. I want to retrieve the last number in the series and that changes so I can't use a set number. I have tried using charAt(n-1) but that gives me a funky number that does do what I want. What I would like to see is if the last digit is 9, I want to see 9. How would be the best way to go about this?
|
 |
Layne Lund
Ranch Hand
Joined: Dec 06, 2001
Posts: 3061
|
|
If you first initialize n with: n = last.length() then your proposed solution should work.
|
Java API Documentation
The Java Tutorial
|
 |
Candy Bortniker
Ranch Hand
Joined: Mar 17, 2003
Posts: 123
|
|
That's what I thought but it doesn't seem to be working that way. Here is my code: What I get for number is something like "52".
|
 |
David Peterson
author
Ranch Hand
Joined: Oct 14, 2001
Posts: 154
|
|
Try:
|
 |
Gabriel White
Ranch Hand
Joined: Mar 02, 2003
Posts: 233
|
|
Yeah this works:
|
 |
Layne Lund
Ranch Hand
Joined: Dec 06, 2001
Posts: 3061
|
|
Originally posted by Candy Bortniker: That's what I thought but it doesn't seem to be working that way. Here is my code: What I get for number is something like "52".
This is because last is the char representation of the digit. When you cast it to a long, you get the Unicode value of the character, which is obviously not what you expected. To get the result you want, you can use the above suggestion: number = (long)(last = '0'); HTH Layne
|
 |
Layne Lund
Ranch Hand
Joined: Dec 06, 2001
Posts: 3061
|
|
|
I should note that this is only useful if you really want the int (or long) representation of the digit. If you are simply printing it out, you shouldn't waste your time and use the char representation instead.
|
 |
Nancy Dernell
Greenhorn
Joined: Feb 28, 2004
Posts: 3
|
|
I had to do a similar thing - check to see if the last character in a string was "s", if so, take it off: // // if myTimes is 1, and myTimesUnitsDesc ends in "s", strip it off // if (myTimes.intValue() == 1) { int myLength = myTimesUnitsDesc.length(); if (myTimesUnitsDesc.charAt(myLength-1) == 's') { return myTimesUnitsDesc.substring(0,myLength-1); } hope that helps
|
 |
sever oon
Ranch Hand
Joined: Feb 08, 2004
Posts: 268
|
|
There's more than one way to skin a cat : Another approach that will have the bit-twiddlers* climbing the walls: *bit-twiddler--someone willing to endure exercises in mental torture to shave a few microseconds from the execution time of an algorithm Or if you require there be at least one character in the string besides the s (otherwise you want to leave that s alone), just change the * in the pattern string above to a +. sev
|
 |
 |
|
|
subject: substring to just get the last character
|
|
|