3

I need to get the last character of the last input string. I wrote a piece of code that gets the last letter of the first string:

public class LastCharacter { public static void main(String[] args) { String string = args[0]; System.out.println("last character: " + string.substring(string.length() -1)); } } 

How can I get the last character of the last string parameter?

1
  • 6
    "i need to get the last character of the last input string" Try String string = args[args.length-1];, assuming that args.length >= 1. Commented Nov 12, 2013 at 18:53

5 Answers 5

5

You may try like this:-

String str= args[args.length-1]; 

And to get the last character:-

char ch = str.charAt(str.length() - 1); 
Sign up to request clarification or add additional context in comments.

6 Comments

That should be str.length(); String has no public property called length.
@VivinPaliath:- Yes thats correct. Missed that! Updated my answer!
@VivinPaliath:- Not an issue Sir. Sometimes you do have to pay when you do miss small things just to answer it first!
(tl;dr: tl;dr.) Sorry, that was my downvote, because I had really thought that the answer missed addressing half of the question when I read it. It's now a complete answer, so either that was an artifact of voting (too) fast, or I was just tripping. Unfortunately, I can't undo my vote without a logged edit, which I hadn't realized. (Sorry--if you were to find an excuse to edit now, I'd clear the downvote.)
@DavidDuncan:- Not an issue Sir. Although I have edited my answer. If you want you can undo your downvote and possibly give me an upvote ;)
|
3

The last string will be at args.length - 1 in the args array, since arrays are 0-based in Java. This is also true in general for any array; the last element is always at array.length - 1.

So you can do:

String lastString = args[args.length - 1]; Character lastCharacter = lastString.charAt(lastString.length() - 1); 

Comments

1
Int lenght = Args.length; String s = args[length -1]; 

Thats your last string in the input

Comments

1

I really can't understand the description, but based on the title, I think you want

public static void main(String[] args){ if(args != null && args.length > 0){ String lastString = args[args.length-1]; if(lastString.length() > 0){ System.out.println(lastString.charAt(lastString.length() - 1)); } } } 

Comments

0

To get the last string:

String last = args[args.length - 1]; 

To get the last character:

char c = last.charAt(last.length() - 1); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.