VOOZH about

URL: https://www.geeksforgeeks.org/dsa/remove-first-and-last-characters/

⇱ Remove first and last characters - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Remove first and last characters

Last Updated : 7 Jun, 2026

Given a string s, return a substring containing all characters except the first and the last. The length of the s will be greater than 2.

Examples:

Input: s = "Hello"
Output: ell
Explanation: The first and last character are ignored.

Input: s = "World"
Output: orl
Explanation: The first and last characters are ignored.

Using Character Traversal - O(n) Time O(n) Space

The idea is to traverse the string from the second character to the second-last character and append each character to a new string. This new string will contain all characters except the first and last ones.


Output
orl

Time Complexity: O(n)
Auxiliary Space: O(n)

Using Built-in Substring/Slicing Function - O(n) Time and O(n) Space

The idea is to directly use the built-in substring/slicing function provided by the language. Since we need to ignore the first and last characters, we start from index 1 and take length - 2 characters.

Built-in Substring/Slicing Functions in Different Languages:

C:

  • C does not provide a built-in string slicing function. We can use functions like strncpy() to copy the required portion of the string into a new character array.
  • The substring starts from index 1 and has length strlen(s) - 2.

C++:

  • C++ provides the substr() function of the string class to extract a substring.
  • We can directly use s.substr(1, s.length() - 2) to remove the first and last characters.

Python:

  • Python supports string slicing using the slice operator [:].
  • The expression s[1:-1] returns all characters except the first and the last.

JavaScript:

  • JavaScript provides methods such as slice() and substring() for extracting substrings.
  • The required substring can be obtained using s.slice(1, -1), which excludes the first and last characters.

Java:

  • Java provides the substring() method of the String class for extracting a part of a string.
  • The required substring can be obtained using s.substring(1, s.length() - 1).

C#:

  • C# provides the Substring() method of the String class.
  • We can start from index 1 and extract s.Length - 2 characters using s.Substring(1, s.Length - 2).

Output
orl

Time Complexity: O(n)
Auxiliary Space: O(n)

Comment
Article Tags:
Article Tags: