This language bar is your friend. Select your favorite languages!
Select your favorite languages :
- Or search :
Idiom #46 Extract beginning of string (prefix)
Create the string t consisting of the 5 first characters of the string s.
Make sure that multibyte characters are properly handled.

- 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
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.
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