Be concise.
Be useful.
All contributions dictatorially edited by webmasters to match personal tastes.
Please do not paste any copyright violating material.
Please try to avoid dependencies to third-party libraries and frameworks.
- Python
- Python
- JS
- JS
- Elixir
- Ada
- C
- Clojure
- C++
- C#
- D
- Dart
- Erlang
- Fortran
- Go
- Groovy
- Haskell
- Java
- Kotlin
- Lisp
- Lua
- Obj-C
- PHP
- Pascal
- Pascal
- Perl
- Ruby
- Rust
- Rust
- Rust
- Scala
- Scheme
- Smalltalk
- VB
t = s[slice(i, j)]
Python 3
let t = s.slice(i, j);
let t = s.substring(i, j);
t = String.slice(s, i..j-1)
T : String := S (I .. J - 1);
In Ada, strings use 1-based indexing
In Ada, J is included by default when slicing
In Ada, J is included by default when slicing
(def t (subs s i j))
Uses String.substring (Java) internally
auto t = s[i .. j];
var t = s.substring(i, j);
T = string:sub_string(I, J-1).
Erlang uses 1-based lists
character(len=:), allocatable :: t
t = s(i:j-1)
In Fortran, characters start with index one.
t := string([]rune(s)[i:j])
convert to []rune because some characters are two or more bytes.
t = drop i (take j s)
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
$t = mb_substr($s, $i, $j-$i, 'UTF-8');
Requires multibyte (mb) extension for unicode support.
t := copy(s,i+1,j-i);
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
val t = s.substring(i, j)
(define t (substring s i j))
Chez Scheme
t := s copyFrom: i to: j - 1.
In Smalltalk, collections (including String) use 1-based indexing.
Dim t As String = s.Substring(i,j)