views:

85

answers:

3

I'm trying to parse though a string made up of a single word.

How would you go about assigning the last letter of the word to a variable?

I was thinking of using the Scanner class to parse the word and make each letter an element in an array but it seems Scanner.next() only goes through whole words and not the individual letters.

Any help?

EDIT: Thanks so much for your help guys. It looks like I was overthinking it as I didn't know about charAt(). Much simpler now. Also, i'm amazed at how fast the responses are on here, it's a god send especially as I've got an assignment due in tomorrow and I think I might be in for an all-nighter.

+6  A: 
String str = "the rain in spain";
System.out.println(str.charAt(str.length() - 1));
nc3b
Only thing is `String` has a capital S ;-)
Finbarr
@Finbarr: edited :">
nc3b
+1  A: 

You can use the length() and charAt() methods. Here's an example to get you started:

String test = "ABC123";

for (int i = 0; i < test.length(); i++)
{
    char myChar = test.charAt(i);

    // etc.
}
Andy White
+1 for giving a general case (i.e. not just the last character but accessing any character in the string.)
DJTripleThreat
+3  A: 

It sounds like you're overthinking it. Why not just do

String x = "abcde";
char y = x.charAt(x.length() - 1);
Matt Ball
same answer already given by nc3b.
Finbarr
Yeah, a few of us all responded at the same time. It's not the end of the world.
Matt Ball
Yeah I suppose you're right.
Finbarr