0

//For each string of array args print the string, its length, its first symbol, and its last symbol.

public class A8b {
    public static void main(String[] args) {
        int i = 0;
        for(i = 0; i < args.length; i++) {
            System.out.println(args[i]); //print the string
            System.out.println(args[i].length()); //length of string
            System.out.println(args[i].substring(0,1)); //its first symbol
            System.out.println(args[i].length()-1); //its last symbol  <<----------
        }
    }
}

So my question is how to print the last symbol of string? I'm trying to do it this way

System.out.println(args[i].length()-1);//its last symbol

but it gives me a wrong answer. Does anybody can help me?

takendarkk
  • 3,347
  • 8
  • 25
  • 37

3 Answers3

0

From a basic string str, to get the last char you can to substring at the indexlength-1 : str.substring(str.length()-1)

So here : args[i].substring(args[i].length-1)

azro
  • 53,056
  • 7
  • 34
  • 70
0

If you know how to get the first character, you can do the same with substring to get the last, but just point it to the last character:

int lastIdx = args[i].length()-1;
System.out.println(args[i].substring(lastIdx)); //its last symbol 

Alternatively, you can use charAt(index_of_last_char):

System.out.println(args[i].charAt(lastIdx)); //its last symbol 
user3437460
  • 17,253
  • 15
  • 58
  • 106
0

From javadoc: https://docs.oracle.com/javase/9/docs/api/java/lang/String.html#substring-int-int-

public String substring​(int beginIndex,
                        int endIndex)

Returns a string that is a substring of this string. The substring begins at the specified beginIndex and extends to the character at index endIndex - 1. Thus the length of the substring is endIndex-beginIndex.

Examples:

     "hamburger".substring(4, 8) returns "urge"
     "smiles".substring(1, 5) returns "mile"


Parameters:
    beginIndex - the beginning index, inclusive.
    endIndex - the ending index, exclusive.

So in your case code for extract last symbol from string will be like that:

String abc = "abc";
String c = abc.substring(abc.length() - 1, abc.length());
System.out.println(c); // c
fxrbfg
  • 1,756
  • 1
  • 11
  • 17