Polyglot CheatSheet - String

Updated: 2019-01-13

String Format

Java

DecimalFormat df = new DecimalFormat("#.###");
df.format(number);

Scala

scala> "%02d".format(1)
res0: String = 01

Python

>>> "%02d" % 1
'01'

Substring

Javascript

str.substring(startIndex, endIndex);
  • startIndex: required, inclusive
  • endIndex: optional, exclusive

Starts With

Python

>>> 'asdf'.startswith('as')
True

Javascript

> "asdf".startsWith("as")
true

Trim

Python

>>> ' asdf '.strip()
'asdf'

Javascript

> " asdf ".trim()
"asdf"

Split

PHP

$parts = Str::explode('_', $raw);

Hack

$parts = Str\split($raw, '_');

Or

list($part1, $part2, $part3) = Str\split(",", $raw);

Python

>>> "a b c".split()
['a', 'b', 'c']

Repeated Characters

Python

>>> 'a' * 10
'aaaaaaaaaa'

Java

jshell> String s = IntStream.range(0, 10).mapToObj(i -> "a").collect(Collectors.joining(""))
s ==> "aaaaaaaaaa"