string manipulation
character extraction
programming tips
coding tutorial
string functions

How do I get the last character of a string?

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

Getting the last character of a string is a small operation, but it exposes an important rule that varies across languages: how string indexing works and what happens when the string is empty. A correct answer should handle both the normal case and the edge case explicitly.

Python: Negative Indexing

Python makes this very simple with negative indexes. -1 refers to the last character.

python
text = "hello"
last_char = text[-1]
print(last_char)

This is concise and readable, but it raises IndexError if text is empty.

python
1text = ""
2
3if text:
4    print(text[-1])
5else:
6    print("String is empty")

That guard is important whenever the string may be empty.

JavaScript: Use length - 1

JavaScript strings do not support negative indexing in ordinary bracket access, so the usual solution is str[str.length - 1].

javascript
const text = "hello";
const lastChar = text[text.length - 1];
console.log(lastChar);

For an empty string, text[text.length - 1] evaluates to undefined, which is safer than an exception but still something you should handle deliberately.

javascript
1function getLastCharacter(text) {
2  return text.length === 0 ? null : text[text.length - 1];
3}
4
5console.log(getLastCharacter("hello"));
6console.log(getLastCharacter(""));

Java: charAt(length - 1)

In Java, strings expose charAt, so the standard form is:

java
1public class LastCharacterDemo {
2    public static void main(String[] args) {
3        String text = "hello";
4        char last = text.charAt(text.length() - 1);
5        System.out.println(last);
6    }
7}

If the string is empty, charAt throws StringIndexOutOfBoundsException. Guard the call if emptiness is possible.

java
1public static Character getLastCharacter(String text) {
2    if (text == null || text.isEmpty()) {
3        return null;
4    }
5    return text.charAt(text.length() - 1);
6}

C#: Indexing Works Similarly

C# uses the same general idea as Java for strings.

csharp
1using System;
2
3class Program
4{
5    static void Main()
6    {
7        string text = "hello";
8        char last = text[text.Length - 1];
9        Console.WriteLine(last);
10    }
11}

Again, this must be guarded if the string might be empty.

A Reusable Helper Is Often Better

If the codebase performs this check often, a helper makes intent clearer and centralizes the edge-case rule.

python
1def get_last_character(text: str) -> str | None:
2    if not text:
3        return None
4    return text[-1]
5
6
7print(get_last_character("codemia"))
8print(get_last_character(""))

That makes callers think in terms of the business rule rather than the indexing syntax.

Characters Versus Unicode Details

This is the part many short answers skip. In some languages and runtimes, "last character" can be trickier when the text contains Unicode characters made from multiple code units or combining marks.

For everyday ASCII or ordinary text, the standard indexing examples above are usually fine. If you are processing user-visible text across many languages, be careful: what a human sees as one character is not always one underlying storage unit.

That concern matters most in text editors, UI rendering code, and advanced normalization work. For most application logic, the ordinary string APIs are acceptable.

Choose Behavior for Empty Strings

There is no universal best behavior for an empty string. Common options are:

  • raise an exception
  • return null or None
  • return an empty string

The important part is to choose one rule deliberately instead of letting each call site behave differently by accident.

Common Pitfalls

The biggest pitfall is forgetting the empty-string case. The indexing syntax is easy, but empty input often appears in real systems through forms, APIs, and optional values.

Another issue is assuming every language supports negative indexing. Python does, but JavaScript and Java do not.

Developers also confuse a visible character with a single storage unit in Unicode-heavy text. That only matters in more advanced text processing, but it is still worth knowing.

Finally, do not overcomplicate simple cases. If your input is ordinary non-empty text in one language, the direct indexing approach is usually enough.

Summary

  • In Python, use text[-1] after guarding against empty strings.
  • In JavaScript, use text[text.length - 1].
  • In Java and C#, use the last valid index with charAt or bracket access.
  • Always decide how your code should behave for empty input.
  • Be aware that visible Unicode characters can be more complex than a single code unit.

Course illustration
Course illustration

All Rights Reserved.