bananamana
bananamana

Reputation: 31

In Java, how do you parse through a single word string?

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

Answers (4)

Brendan Cronan
Brendan Cronan

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

nc3b
nc3b

Reputation: 16270

String str = "the rain in spain";
System.out.println(str.charAt(str.length() - 1));

Upvotes: 6

Matt Ball
Matt Ball

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

Andy White
Andy White

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

Related Questions