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.
- Ada
- Clojure
- Cobol
- C++
- C#
- D
- Dart
- Elixir
- Erlang
- Erlang
- Fortran
- Go
- Go
- Groovy
- Groovy
- Haskell
- Haskell
- JS
- Java
- Kotlin
- Lisp
- Lua
- Obj-C
- PHP
- Pascal
- Perl
- Python
- Ruby
- Ruby
- Ruby
- Rust
- Rust
- Scala
- Smalltalk
T : String := S (1 .. 5);
IDENTIFICATION DIVISION.
PROGRAM-ID. prefix 5.
PROCEDURE DIVISION.
MOVE s(1:5) TO t
STOP RUN.
auto t = s.substr(0, 5);
The way of handling multibyte characters depends on the exact type of s, e.g. string, wstring, etc.
string t = s[0..5];
character(len=5) :: t
t = s(1:5)
i := 0
count := 0
for i = range s {
if count >= 5 {
break
}
count++
}
t := s
if count >= 5 {
t = s[:i]
}
This does not allocate
t :: T.Text
t = T.take 5 s
This implementation uses the Text type, imported as suggested in the Text library documentation.
t :: String
t = take 5 s
The function take has two arguments: the number of characters to take as a prefix, and the string to take the prefix from. The function take is in the Haskell prelude and doesn't need to be imported.
The type signature is optional, and could be omitted leaving the second line.
The type signature is optional, and could be omitted leaving the second line.
String t = s.substring(0,5);
s must not be null.
val t = s.take(5)
(setf *t* (subseq s 0 5))
t = s:sub(1,5)
$t = mb_substr($s, 0, 5, 'UTF-8');
Requires the non-default extension mbstring
_t := Copy(_s, 1, 5);
The code is safe even if s has less than 5 characters.
my $t = substr($s,0,5);
t = s[:5]
let t = s.char_indices().nth(5).map_or(s, |(i, _)| &s[..i]);
Rust strings are encoded in UTF-8, and can be multiple bytes wide, which text processing code must account for. Naively slicing the string could cause it to panic if, for example, the string contained 😁
It should be noted that these logical "characters" don't have much semantic meaning either: Unicode characters are combined into "graphemes" before being displayed to the user, which would need to be identified using the unicode-segmentation crate
It should be noted that these logical "characters" don't have much semantic meaning either: Unicode characters are combined into "graphemes" before being displayed to the user, which would need to be identified using the unicode-segmentation crate
let t = s.chars().take(5).collect::<String>();
s first: 5