This language bar is your friend. Select your favorite languages!
Select your favorite languages :
- Or search :
Idiom #38 Extract a substring
Find substring t consisting in characters i (included) to j (excluded) of string s.
Character indices start at 0 unless specified otherwise.
Make sure that multibyte characters are properly handled.

- Ada
- C
- Clojure
- C++
- C#
- D
- Dart
- Elixir
- Erlang
- Fortran
- Go
- Groovy
- Haskell
- JS
- JS
- Java
- Kotlin
- Lisp
- Lua
- Obj-C
- PHP
- Pascal
- Pascal
- Perl
- Python
- Python
- Ruby
- Rust
- Rust
- Rust
- Scala
- Scheme
- Smalltalk
- VB
String t = s.substring(i,j);
Throws IndexOutOfBoundsException if i is negative, or j is larger than the length of s, or i is larger than j.
(setf u (subseq s i j))
t is not a good choice for a variable name in Lisp, so using u instead for the result string
local t = s:sub(i, j - 1)
In Lua, strings use 1-based indexing
Lua has pure-byte strings and doesn't support Unicode by default.
Lua has pure-byte strings and doesn't support Unicode by default.
t=[s substringWithRange:NSMakeRange(i,j-i)]
A range contains the initial index and the length of the part needed
my $chunk = substr("now is the time", $i, $j);
Perl is 0-based: i=3 would start at the 4th character.
let mut iter = s.grapheme_indices(true);
let i_idx = iter.nth(i).map(|x|x.0).unwrap_or(0);
let j_idx = iter.nth(j-i).map(|x|x.0).unwrap_or(0);
let t = s[i_idx..j_idx];
Avoid building a new string
programming-idioms.org