Polyglot CheatSheet - String

Updated: 2021-11-28

String Comparison

C++

string::operator==() is equivalent to string::compare()

str1 == str2

Substring

Javascript

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

Starts With

C++

#include "absl/strings/match.h"
absl::StartsWith(str, prefix)

Python

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

Javascript

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

Trim / Strip

C++

Strip prefix

absl::StripPrefix

Java

// since Java 11
stripLeading()
stripTrailing()

// Removes the white space from both ends
// Unicode-aware
// since Java 11
strip()

// Removes the white space from both ends
// only characters <= U+0020 (space)
trim()

Python

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

Javascript

> " asdf ".trim()
"asdf"

Remove Prefix

Javascript

"www.example.com".replace("www.", "");
"www.example.com".replace(/^www\./, "");;
"www.example.com".slice(4);

Split

C++

use absl::StrSplit() from absl/strings/str_split.h

// Using std::string elements will make a copy of the pieces.
std::vector<std::string> letters = absl::StrSplit("a b c d e f",
                                                   absl::ByChar(' '));
// The string_views refer to memory from the input string.
std::list<absl::string_view> words = absl::StrSplit("the:quick;brown,fox",
                                                    absl::ByAnyChar(":;,"));

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"

Join

C++

#include "third_party/absl/strings/str_join.h"
absl::StrJoin(std::make_tuple(a, b, c), "|");

Java

String.join(",", list);

Go

strings.Join(arr, ",")

SQL

SELECT ARRAY_TO_STRING(arr, ",")
FROM ...