Reputation: 31
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.
Upvotes: 1
Views: 2669
Reputation: 349
just use substring method and other simple java String methods they are pretty useful.
int length = inputWord.length();
int last = length-1;
String lastLetter = inputWord.substring(last);
not hugely difficult but you are probably over thinking it.
Upvotes: 0
Reputation: 16270
String str = "the rain in spain";
System.out.println(str.charAt(str.length() - 1));
Upvotes: 6
Reputation: 360056
It sounds like you're overthinking it. Why not just do
String x = "abcde";
char y = x.charAt(x.length() - 1);
Upvotes: 3
Reputation: 88475
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.
}
Upvotes: 1