Subscribe to Coding Beauty Newsletter
Gain useful insights and advance your web development knowledge with weekly tips and tutorials from Coding Beauty. Over 2,000 developers subscribe.
1. String at() Method
The get the last character of a string, we can call the
2. String charAt() Method
Alternatively, to get the last character of a string, we can call the
4 method on the string, passing the last character index as an argument. For example,
5 returns a new string containing the last character of
4 method takes an index and returns the character of the string at that index.
9, and the last character has an index of
If we pass an index to
4 that doesn’t exist on the string, it returns an empty string (
3. Bracket Notation () Property Access
We can also use the bracket notation (
3) to access the last character of a string. Just like with the
4 method we use
0 as an index to access the last character.
4, using the bracket notation to access a character at a non-existent index in the string will return
4. String split() and Array pop() Methods
With this method, we call the
8 method on the string to get an array of characters, then we call
9 on this array to get the last character of the string.
We passed an empty string (
2) to the
8 method to split the string into an array of all its characters.
9 method removes the last element from an array and returns that element. We call it on the array of characters to get the last character.
Sign up and receive a free copy immediately.
Ayibatari Ibaba is a software developer with years of experience building websites and apps. He has written extensively on a wide range of programming topics and has created dozens of apps and open-source libraries.
How do you find the first and last character of a string?
The idea is to use charAt() method of String class to find the first and last character in a string. The charAt() method accepts a parameter as an index of the character to be returned. The first character in a string is present at index zero and the last character in a string is present at index length of string-1.
How do you trim first and last characters?
The idea is to use the substring() method of String class to remove first and the last character of a string. The substring(int beginIndex, int endIndex) method accepts two parameters, first is starting index, and the second is ending index.