Programming Language Cheat Sheets: Strings

Programming language cheat sheets for 20+ languages. Strings Mathematics [Format] Operators and Symbols [string interpolation] General (Control Flow/Debugging) [multi-line strings] Dates Objects [Array.Join/Array.ToString, Array.Print/Map.Print] New Features Timelines Documentation Links [format/sprintf, escape chars] Sections: String Functions The Universal Function Library Project: Details Note: UFL: Universal Function Library, a set of 1000+ standard functions for all programming languages. Languages do not have to implement anything exactly to the UFL specification, it is a guide. See lower down for further details.

String Functions

UFL: (StringNewDemo) [or StrNewDemo][create a string][see also: VarDeclSet/VarDeclSetAuto/JsonArrayDemo/JsonObjectDemo] Prompt: MyLang, one-liner, output var vText (string). vText equals "abc". As a comment, state the type of vText. AutoHotkey: vText := "abc" [type: String] [note: mutation: StrPtr() gives you a string pointer, allowing in-place modification via NumPut()/StrPut()/DllCall(). C++: std::string vText = "abc" [type: std::string (typeid: NSt3__212basic_stringIcNS_11char_traitsIcEENS_9allocatorIcEEEE)] [WARNING: auto vText = "abc" resolves to type 'const char *' (typeid: 'PKc') (i.e. char array, not std::string)] C#: var vText = "abc" [type: String] [also: string vText = "abc"] [note: 'var'/'string'/'String' resolve to String] Crystal: vText = "abc" [type: String] [also: vText: String = "abc"] Excel: abc [type: 2 (Text)] Excel VBA: vText = "abc" [type: String] Go: vText := "abc" [type: string] [also: var vText string = "abc"] [also: var oSB strings.Builder] [type (Builder): strings.Builder] Java: var vText = "abc" [type: String] [also: String vText = "abc"] [note: 'var'/'String' resolve to String] JavaScript: vText = "abc" [type: string] [also (rarely used, type 'object'): oObj = new String("abc")] Kotlin: var vText = "abc" [type: String] [also: var vText: String = "abc"] PHP: $vText = "abc" [type: string] Python: vText = "abc" [type: str] [also (type hint): vText: str = "abc"] R: vText = "abc" [type: character] [WARNING: 'character', not 'string'] [MAJOR WARNING: in R, a value is equivalent to a 1-item vector, so in other languages it would be like "abc" equals ["abc"], "" equals [""], but "" doesn't equal []] [note: "" equals character(1) (a 1-item vector), not character(0) (a 0-item vector), e.g. identical("", character(1)) returns TRUE] [MAJOR WARNING: various string functions do literal or RegEx manipulation depending on settings params, e.g. 'fixed=TRUE' (literal), e.g. 'perl=TRUE' (PCRE RegEx), e.g. omitted (typically 'extended' POSIX ERE RegEx)] Ruby: vText = "abc" [type: String] [note: mutation: in-place modification possible via methods such as prepend()/insert()/concat()/replace()/clear, and various functions ending in '!'] Rust: let mut vText = "abc" [type: &str] [also: let mut vText = "abc".to_string()] [type (to_string): String] [also: let mut vText: &str = "abc"] [also: let mut vText: String = "abc".to_string()] [also: let mut vText = String::from("abc")] [also (blank string): let mut vText = String::new()] Scala: var vText = "abc" [type: String] [also: var vText: String = "abc"] SQL (MySQL): ___ [can use (create table, insert row): CREATE TABLE MyTable (k TEXT, v TEXT); INSERT INTO MyTable VALUES ('MyKey','abc');] [type: text] SQL (PostgreSQL): ___ [can use (create table, insert row): CREATE TABLE MyTable (k TEXT, v TEXT); INSERT INTO MyTable VALUES ('MyKey','abc');] [type: text] [can use (variables exist only within the statement) WITH MyVars (vText1, vText2) AS (VALUES ('abc', 'def')) SELECT * FROM MyVars] SQL (SQLite): ___ [can use (create table, insert row): CREATE TABLE MyTable (k TEXT, v TEXT) STRICT; INSERT INTO MyTable VALUES ('MyKey','abc');] [type: text] Swift: var vText = "abc" [type: String] [also: var vText: String = "abc"] UFL: (CharNewDemo) [create a character][see also: IntToChar/StrToChar] Prompt: MyLang, one-liner, output var vChar (char). vChar equals 'a'. As a comment, state the maximum value for a char, and state the type of vChar. If the language lacks a 'char' type, show '___'. AutoHotkey: ___ C++: auto vChar = 'a' [e.g. (UTF-8 byte)] [type: char (typeid: c)] [note: 'auto'/'char' resolve to 'char'] C#: var vChar = 'a' [e.g. (UTF-16 short)] [type: Char] [note: 'var'/'char'/'Char' resolve to Char] Crystal: vChar = 'a' [e.g. (codepoint)] [type: Char] Excel: ___ Excel VBA: ___ Go: ___ [note: there is no 'char' type, e.g. creates an int32: vChar := 'a'] [type ('a'): int32] Java: var vChar = 'a' [e.g. (UTF-16 short)] [type: char] [note: 'var'/'char' resolve to char] [note: 'char' (lower case), 'String' (title case)] JavaScript: ___ Kotlin: var vChar = 'a' [e.g. (UTF-16 short)] [type: Char] PHP: ___ Python: ___ R: ___ Ruby: ___ Rust: let mut vChar = 'a' [e.g. (codepoint)] [type: char] Scala: var vChar = 'a' [e.g. (UTF-16 short)] [type: char] SQL (MySQL): ___ SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: var vChar: Character = "a" [e.g. (codepoint)] [type: Character] [also: var vChar = Array("a")[0]] [note: can't use single quotes to create a char] UFL: (StringNewDemoAscii) [or StrNewDemoAscii/StrNewDemoEveryChar/StrNewDemoAllChar/StrNewDemoCharZoo][create a string containing ASCII chars 33-126 (94 chars): !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~][see also: SymEscape/IntToStrCharEscapeDemo/StrMultiLineDemo] Prompt: MyLang, one-liner, output var vText (string). vText equals chars 33 to 126 inclusive. As a comment, list any chars that were escaped. AutoHotkey: vText := "!`"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_``abcdefghijklmnopqrstuvwxyz{|}~" [note: escaped chars: "`] [note: AHK v1: " is escaped via ""] C++: std::string vText = "!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~" [note: escaped chars: "\] C#: var vText = "!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~" [note: escaped chars: "\] Crystal: vText = "!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~" [note: escaped chars: "\] Excel: ="!""#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~" [also: can type the literal string verbatim] [note: escaped chars: "] Excel VBA: vText = "!""#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~" [note: escaped chars: "] Go: vText := "!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~" [note: escaped chars: "\] Java: var vText = "!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~" [note: escaped chars: "\] JavaScript: vText = "!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~" [note: escaped chars: "\] Kotlin: var vText = "!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~" [note: escaped chars: "\] PHP: $vText = "!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~" [note: escaped chars: "\] Python: vText = "!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~" [note: escaped chars: "\] R: vText = "!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~" [note: escaped chars: "\] Ruby: vText = "!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~" [note: escaped chars: "\] Rust: let vText = "!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~" [note: escaped chars: "\] Scala: var vText = "!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~" [note: escaped chars: "\] SQL (MySQL): ___ [can use: SELECT '!"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~'] [note: escaped chars: '\] [also: dual quoting: e.g. 'a''b'] SQL (PostgreSQL): ___ [can use: SELECT '!"#$%&''()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~'] [note: escaped chars: '] SQL (SQLite): ___ [can use: SELECT '!"#$%&''()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~'] [note: escaped chars: '] Swift: var vText = "!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~" [note: escaped chars: "\] UFL: (StringNewDemoAsciiVerbatim) [or StringNewDemoAsciiRaw][create a raw/verbatim string literal containing ASCII chars 33-126 (where none of the chars are escaped)][see also: SymVerbatim] Prompt: MyLang, one-liner, output var vText (string). vText equals a verbatim string literal containing chars 33 to 126 inclusive, where none of the chars are escaped. If such a string can't be created without escaping at least one char, show '___', and as a comment, show a string literal with as few chars escaped as possible. AutoHotkey: ___ [can use (replace pilcrows with line breaks, continuation section): vText := "¶(`¶!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~¶)"] [defunct: AHK v1: " must be doubled] [note: ` is used in the options line to make it literal (other options include Join/Comments/LTrim0)] [WARNING: a closing parenthesis at the start of a line neededs escaping: '`)'] C++: std::string vText = R"(!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~)" [can use: R"mytag(abc)mytag" to handle ')"'] C#: string vText = """!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~""" [note: can't be done via verbatim string literals ('@'): " needs escaping] [can use: add more leading/trailing quotes to handle multiple consecutive quotes] Crystal: vText = %q(!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~) [WARNING: '%q(' could fail depending on the number of parentheses in the verbatim string, workaround: use an alternative delimiter e.g. '%q[mytext]', '%q!mytext!'] [WARNING: '\' escapes '\' and the trailing delimiter char] Excel: ___ Excel VBA: ___ Go: ___ [note: can't be done via raw string literals ('`'): '`' can't appear in raw string literals] Java: ___ [note: can't be done via text blocks ("""): '\' needs escaping] JavaScript: ___ [note: can't be done via template literals ('`') or String.raw: '`' needs escaping] Kotlin: var vText = """!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~""" [WARNING: '$' does interpolation depending on the subsequent chars, workaround: multi-dollar interpolation] [WARNING: can't handle literal '"""' unless use interpolation] PHP: ___ [can use (replace pilcrows with line breaks, Nowdoc): $vText = <<<'EOT'¶!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~¶EOT;] Python: vText = r"""!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~""" [WARNING: doesn't allow trailing '\'] R: vText = r"(!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~)" [can use: can change the delimiter chars, or add 2 or more hyphens to each end, to handle string clashes] Ruby: vText = %q(!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~) [WARNING: '%q(' could fail depending on the number of parentheses in the verbatim string, workaround: use an alternative delimiter e.g. '%q[mytext]', '%q!mytext!'] [WARNING: '\' escapes '\' and the trailing delimiter char] Rust: let vText = r##"!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~"## [can use: add more leading/trailing hashes to handle multiple consecutive hashes] Scala: var vText = """!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~""" [WARNING: can't handle literal '"""'] SQL (MySQL): ___ SQL (PostgreSQL): SELECT $$!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~$$ [also: handle consecutive dollar signs: $mytag$abc$mytag$] SQL (SQLite): ___ Swift: var vText = ##"!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~"## [can use: add more leading/trailing hashes to handle multiple consecutive hashes] UFL: (StringNewDemoLineFeed) [create a string containing a linefeed][see also: Chr] Prompt: MyLang, multiple one-liners, output var vLF (string). vLF equals char 10 as a string, demonstrate common approaches. AutoHotkey: vLF := "`n" [also: Chr(10)] [also: Format("{:c}", 10)] C++: vLF = "\n" [also: (std::string){(char)10}] [also: std::string vLF{(char)10}] C#: vLF = "\n" [also: Char.ConvertFromUtf32(10)] Crystal: vLF = "\n" [also: 10.chr.to_s] Excel: =CHAR(10) [also: =UNICHAR(10)] Excel VBA: vLF = vbLf [also: ChrW(10)] Go: vLF := "\n" [also: string(rune(10))] Java: vLF = "\n" [also: vLF = new String(new int[]{10}, 0, 1)] [also: Character.toString(10)] [also: new String(Character.toChars(10))] JavaScript: vLF = "\n" [also: String.fromCodePoint(10)] [also: String.fromCharCode(10)] Kotlin: vLF = "\n" [also: Character.toString(10)] PHP: vLF = "\n" [also: mb_chr(10)] Python: vLF = "\n" [also: chr(10)] R: vLF = "\n" [also: intToUtf8(10)] Ruby: vLF = "\n" [also: 10.chr.to_s] [also: 10.chr(Encoding::UTF_8)] Rust: vLF = "\n" [also: char::from_u32(10 as u32).unwrap().to_string()] Scala: vLF = "\n" [also: String(Array(10), 0, 1)] [also: Character.toString(10)] [also: String(Character.toChars(10))] [also: 10.toChar.toString] SQL (MySQL): '\n' [also: char(10)] SQL (PostgreSQL): E'\n' [also: chr(10)] [also: unistr('\u000A')] SQL (SQLite): x'0a' [also: char(10)] [also: unistr('\u000A')] Swift: vLF = "\n" [also: String(UnicodeScalar(10)!)] UFL: (StringNewDemoQuote) [create a string containing a double quote][note: '\x22' is useful for simple parsing, where " only means string start/end][see also: Chr] Prompt: MyLang, multiple one-liners, output var vDQ (string). vDQ equals char 34 as a string, demonstrate common approaches. AutoHotkey: vDQ := "`"" [also: vDQ := '"'] [also: vDQ := Chr(0x22)] [also: vDQ := Format("{:c}", 0x22)] C++: std::string vDQ = "\"" [also: auto vDQ = std::string("") + '"'] [also: std::string vDQ = "\u0022"] [also: auto vDQ = (std::string){'"'}] [also: std::string vDQ{'"'}] [also: auto vDQ = (std::string){(char)0x22}] [also: std::string vDQ{(char)0x22}] [WARNING: \x has max 255 but consumes as many hex chars as possible] [note: doesn't work: std::string vDQ = '"'] C#: vDQ = "\"" [also: vDQ = "" + '"'] [also: vDQ = "\u0022"] [also: vDQ = "\x0022"] [also: vDQ = "" + (char)0x22] [also: vDQ = Char.ConvertFromUtf32(0x22)] Crystal: vDQ = "\"" [also: vDQ = "" + '"'] [also: vDQ = "\x22"] [also: vDQ = 0x22.chr.to_s] Excel: " [also: =""""] [also: =CHAR(HEX2DEC("22"))] [also: =CHAR(34)] Excel VBA: vDQ = """" [also: vDQ = ChrW(&H22)] Go: vDQ := "\"" [also: vDQ := string('"')] [also: vDQ := "\x22"] [also: vDQ := string(rune(0x22))] [note: there is no 'char' type, e.g. 'a' creates an int32] [note: Go vet warns if 'string(0x22)' is used, use 'string(rune(0x22))' instead] Java: vDQ = "\"" [also: vDQ = "" + '"'] [also: vDQ = "\u005C\u0022"] [also: vDQ = new String(new int[]{0x22}, 0, 1)] [also: vDQ = Character.toString(0x22)] [also: vDQ = new String(Character.toChars(0x22))] [also: vDQ = "" + (char)0x22] [MAJOR WARNING: Java replaces escaped chars, including in comments, before parsing the source code] [note: no \x] JavaScript: vDQ = "\"" [also: vDQ = '"'] [also: vDQ = "\x22"] [also: vDQ = String.fromCodePoint(0x22)] [also: vDQ = String.fromCharCode(0x22)] [also: vDQ = "\u0022"] Kotlin: vDQ = "\"" [also: vDQ = "" + '"'] [also: vDQ = '"'.toString()] [also: vDQ = "\u0022"] [also: vDQ = Character.toString(0x22)] [also: vDQ = 0x22.toChar().toString()] [note: no \x] [note: doesn't work: String('"')] PHP: vDQ = "\"" [also: vDQ = '"'] [also: vDQ = "\x22"] [also: vDQ = mb_chr(0x22)] Python: vDQ = "\"" [also: vDQ = '"'] [also: vDQ = "\x22"] [also: vDQ = chr(0x22)] R: vDQ = "\"" [also: vDQ = '"'] [also: vDQ = "\x22"] [also: vDQ = intToUtf8(0x22)] Ruby: vDQ = "\"" [also: vDQ = '"'] [also: vDQ = "\x22"] [also: vDQ = 0x22.chr.to_s] [also: vDQ = 0x22.chr(Encoding::UTF_8)] Rust: vDQ = "\"" [also: vDQ = "\x22"] [also: vDQ = "\"".to_string()] [also: vDQ = "\x22".to_string()] [also: vDQ = '"'.to_string()] [also: vDQ = (0x22 as char).to_string()] [also: vDQ = char::from(0x22).to_string()] [also: vDQ = char::from_u32(0x22).unwrap().to_string()] [also: can replace '.to_string()' with '.to_string().as_str()'] Scala: vDQ = "\"" [also: vDQ = "" + '"'] [note: '\u0022' within a string causes an error] [also: vDQ = String(Array(0x22), 0, 1)] [also: vDQ = Character.toString(0x22)] [also: vDQ = String(Character.toChars(0x22))] [also: vDQ = 0x22.toChar.toString] [also: vDQ = "" + 0x22.toChar] [note: no \x] SQL (MySQL): '"' [also: "\""] [also (UTF-8 raw bytes as hex): x'22'] [also: char(0x22)] SQL (PostgreSQL): '"' [also: E'\x22'] [also: chr(0x22)] [also: unistr('\u0022')] [also: unistr('\0022')] SQL (SQLite): '"' [also (UTF-8 raw bytes as hex): ''||x'22'] [also: char(0x22)] [also: unistr('\u0022')] [also: unistr('\0022')] Swift: vDQ = "\"" [also: vDQ = "\u{22}"] [also: vDQ = String(UnicodeScalar(0x22)!)] [note: no \x] UFL: (StringNewDemoBackslash) [or StrPathDemo][create literal backslashes, without escaping individual backslashes][e.g. for paths in Windows, e.g. for regular expressions (RegEx)][see also: JsonArrayDemo/JsonObjectDemo/SymInterpolateVarDemo/SymEscape] Prompt: MyLang, multiple one-liners, output var vText (string). Assign string "C:\\MyDir" to vText, use approaches where '\' doesn't need escaping. AutoHotkey: vText := "C:\MyDir" [note: ` is used to escape chars e.g. `t, `n] C++: vText = R"(C:\MyDir)" C#: vText = """C:\MyDir""" [also: vText = @"C:\MyDir"] Crystal: vText = %q(C:\MyDir) Excel: ="C:\MyDir" [note: only escape char is ", escaped as ""] Excel VBA: vText = "C:\MyDir" [note: only escape char is ", escaped as ""] Go: vText := `C:\MyDir` Java: ___ JavaScript: vText = String.raw`C:\MyDir` Kotlin: vText = """C:\MyDir""" PHP: $vText = 'C:\MyDir' [WARNING: '\\' is interpreted as '\', '\'' is interpreted as '''] [note: for comparison: "C:\\MyDir"] Python: vText = r"C:\MyDir" R: vText = r"(C:\MyDir)" [also: vText = r"[C:\MyDir]"] [also: vText = r"{C:\MyDir}"] [note: 'Raw character constants are also available using a syntax similar to the one used in C++'] Ruby: vText = 'C:\MyDir' [WARNING: '\\' is interpreted as '\', '\'' is interpreted as '''] [also: vText = %q(C:\MyDir)] [WARNING (%q): '\\' is interpreted as '\'] [note: for comparison: "C:\\MyDir"] Rust: vText = r#"C:\MyDir"# Scala: vText = """C:\MyDir""" SQL (MySQL): ___ [can use: SET @vSqlMode = @@SESSION.sql_mode; SET @@SESSION.sql_mode = NO_BACKSLASH_ESCAPES; SELECT 'C:\MyDir'; SET @@SESSION.sql_mode = @vSqlMode;] SQL (PostgreSQL): 'C:\MyDir' [note: for comparison: E'C:\\MyDir'] SQL (SQLite): 'C:\MyDir' Swift: vText = #"C:\MyDir"# UFL: (StringNewDemoNull) [create and print a string containing a null char][see also: SymEscape] Prompt: MyLang, one-liner. Create and print a string containing a null char, equivalent to JavaScript: console.log("abc\x00def".length). As a comment, state the output value (the string length). AutoHotkey: MsgBox(StrLen("abc" Chr(0) "def")) [output: 7] [defunct: AHK v1: output is 6, because Chr(0) returns ""] C++: std::cout << std::string("abc\u0000def", 7).size() << "\n"; [output: 7] [WARNING: '\0' and '\x0' work but could become another char based on subsequent chars] C#: System.Console.Write("abc\0def".Length); [output: 7] Crystal: p "abc\u0000def".size [output: 7] [WARNING: '\0' works but could become another char based on subsequent chars] Excel: =LEN("abc"&CHAR(0)&"def") [output: throws] Excel VBA: Debug.Print Len("abc" & Chr(0) & "def") [output: 7] Go: fmt.Print(len("abc\x00def")) [output: 7] [also: '\000'] [note: '\0' is invalid] Java: System.out.println("abc\u0000def".length()); [output: 7] [WARNING: '\0' works but could become another char based on subsequent chars] JavaScript: console.log("abc\x00def".length); [output: 7] [WARNING (with 'use strict' off): '\0' works but could become another char based on subsequent chars] Kotlin: println("abc\u0000def".length) [output: 7] [note: '\0' is invalid] PHP: var_export(strlen("abc\x00def")); echo("\n"); [output: 7] [WARNING: '\0' works but could become another char based on subsequent chars] Python: print(len("abc\x00def")) [output: 7] [WARNING: '\0' works but could become another char based on subsequent chars] R: print(nchar("abc\x00def")) [output: throws] [WARNING: '\0' works but could become another char based on subsequent chars] Ruby: p "abc\u0000def".length [output: 7] [WARNING: '\0' works but could become another char based on subsequent chars] Rust: println!("{}", "abc\0def".len()); [output: 7] Scala: println("abc\u0000def".length) [output: 7] [defunct: '\0'] SQL (MySQL): SELECT char_length('abc\0def'); [also: SELECT char_length(concat('abc', CHAR(0), 'def'));] [output (both): 7] SQL (PostgreSQL): SELECT length(E'abc\x00def'); [also: SELECT length('abc' || CHR(0) || 'def');] [output (both): throws] [WARNING: '\0' works but could become another char based on subsequent chars] SQL (SQLite): SELECT length('abc' || CAST(x'00' AS TEXT) || 'def'); [output: 3 (not 7)] Swift: print("abc\0def".count) [output: 7] UFL: String [or ToString/AnyToString/ValueToString/Str/ToStr/AnyToStr/ValueToStr/VarToStr][anything listed here handles strings/ints/floats/objects, where objects include arrays/maps][see also: NumToString/ObjToString] Prompt: MyLang, one-liner, input var vVar (int), output var vText (string). Convert vVar to a string vText. AutoHotkey: String [e.g. vText := String(vVar)] [note: handles string/int/float and any object with a ToString method] [WARNING: currently doesn't work on built-in Array/Map/Object] C++: ___ [WARNING: no general approaches for primitives/arrays/maps] [WARNING: std::to_string fails on std::string itself] C#: ToString [e.g. vText = vVar.ToString()] [also: "" + vVar] [WARNING: no general approaches for primitives/arrays/maps] Crystal: to_s [e.g. vText = vVar.to_s] Excel: ___ [can use: =""&A1] [also: =A1] Excel VBA: ___ [can use: vText = "" & vText] Go: fmt.Sprintf [e.g. vText := fmt.Sprintf("%v", vVar)] Java: String.valueOf [e.g. vText = String.valueOf(vVar)] [also: "" + vVar] [also: vVar.toString()] [WARNING: no general approaches for primitives/arrays/maps] JavaScript: String [e.g. vText = String(vVar)] [note: works on arrays] [WARNING: only prints '[object Map]' / '[object Object]' for Map/Object types] Kotlin: toString [e.g. vText = vVar.toString()] [WARNING: toString() only prints type name for arrays] [also: oArrayAny.toList().toString()] PHP: var_export [e.g. $vText = var_export($vVar, true)] [also: print_r($vVar, true)] Python: str [e.g. vText = str(vVar)] R: toString [e.g. vText = toString(vVar)] [also: capture.output(print(vVar))] Ruby: to_s [e.g. vText = vVar.to_s] Rust: format [e.g. vText = format!("{}", vVar)] [e.g. format!("{:?}", vVar)] [e.g. format!("{:#?}", vVar)] Scala: toString [e.g. vText = vVar.toString] [WARNING: toString only prints type name for arrays] SQL (MySQL): ___ [can use: '' || MyVar] [also: concat(MyVar)] [also: convert(MyVar, char)] [also (to varchar): CAST(MyVar AS CHAR)] [requires (||): set sql_mode=PIPES_AS_CONCAT] SQL (PostgreSQL): ___ [can use: '' || MyVar] [also: concat(MyVar)] [also: CAST(MyVar AS text)] [also: MyVar::text] SQL (SQLite): ___ [can use: '' || MyVar] [also: concat(MyVar)] [also: CAST(MyVar AS TEXT)] Swift: String [e.g. vText = String(describing:vVar)] [e.g. vVar.description] [e.g. String(reflecting:vVar)] UFL: NumToString [or IntToString/IntegerToString/FloatToString/NumToStr/IntToStr/IntegerToStr/FloatToStr/NumberToStr] Prompt: MyLang, one-liner, input var vNum (int), output var vText (string). Convert vVar to a string vText. AutoHotkey: String [e.g. vText := String(vNum)] C++: std::to_string [e.g. vText = std::to_string(vNum)] C#: ToString [e.g. vText = vNum.ToString()] Crystal: to_s [e.g. vText = vNum.to_s] Excel: TEXT [e.g. =TEXT(A1,"General")] [also: =""&A1] Excel VBA: CStr [e.g. vText = CStr(vNum)] Go: fmt.Sprintf [e.g. vText := fmt.Sprintf("%v", vNum)] Java: String.valueOf [e.g. vText = String.valueOf(vNum)] [also: Integer.toString(vNum)] [also: Double.toString(vNum)] [also: "" + vNum] JavaScript: String [e.g. vText = String(vNum)] [also: vNum.toString()] [also: JSON.stringify(vNum)] Kotlin: toString [e.g. vText = vNum.toString()] PHP: strval [e.g. $vText = strval($vNum)] Python: str [e.g. vText = str(vNum)] R: as.character [e.g. vText = as.character(vNum)] [also: paste(vNum)] [also: toString(vNum)] Ruby: to_s [e.g. vText = vNum.to_s] Rust: to_string [e.g. vText = vNum.to_string()] [also: format!("{}", vNum)] Scala: toString [e.g. vText = vNum.toString] [also: "" + vNum] SQL (MySQL): ___ [can use: '' || MyNum] [also: concat(MyNum)] [also: convert(MyNum, char)] [also (varchar): CAST(MyNum AS CHAR)] [requires (||): set sql_mode=PIPES_AS_CONCAT] SQL (PostgreSQL): ___ [can use: '' || MyNum] [also: CAST(MyNum AS text)] [also: MyNum::text] SQL (SQLite): ___ [can use: '' || MyNum] [also: CAST(MyNum AS TEXT)] Swift: String [e.g. vText = String(vNum)] UFL: ObjToString [or ObjectToString/ObjToStr/ObjectToStr][note: oArrayAny indicates works on int/float/string arrays, oArrayStr indicates works on string arrays only][see also: Array.ToString/Object.ToString/Map.ToString/Set.ToString] Prompt: MyLang, one-liner, input var oObj (object), output var vText (string). Convert oObj to a string vText. AutoHotkey: String [e.g. vText := String(oObj)] [note: handles any object with a ToString method] C++: ___ C#: ___ [can use: vText = String.Join(vSep, oArrayAny)] Crystal: to_s [e.g. vText = oArrayAny.to_s] Excel: ___ Excel VBA: ___ [can use: vText = Join(oArrayAny, vSep)] Go: fmt.Sprintf [e.g. vText := fmt.Sprintf("%v", oArrayAny)] Java: ___ [e.g. vText = java.util.Arrays.toString(oArrayAny)] [e.g. String.join(vSep, oArrayStr)] JavaScript: String [e.g. vText = String(oArrayAny)] [e.g. oArrayAny.join(vSep)] [also: JSON.stringify(oObj)] Kotlin: ___ [e.g. vText = oArrayAny.joinToString(vSep)] [e.g. oArrayAny.toList().toString()] PHP: strval [e.g. $vText = implode($vSep, $oArrayAny)] [e.g. $vText = var_export($oArrayAny, true)] Python: str [e.g. vText = str(oListAny)] [e.g. vSep.join(oListStr)] [e.g. vSep.join(map(str, oListAny))] R: toString [e.g. vText = toString(oVecAny)] Ruby: to_s [e.g. vText = oArrayAny.to_s] Rust: format [e.g. vText = format!("{:?}", oArrayAny)] [e.g. format!("{:#?}", oArrayAny)] Scala: toString [e.g. vText = oObj.toString] [can use: oArrayAny.mkString(vSep)] [WARNING: toString only prints type name for arrays] SQL (MySQL): ___ SQL (PostgreSQL): ___ [can use: CAST(MyObj AS text)] [also: MyObj::text] SQL (SQLite): ___ Swift: String [e.g. vText = String(describing:oArrayAny)] [e.g. oArrayAny.description] [e.g. String(reflecting:oArrayAny)] [e.g. oArrayStr.joined(separator:vSep)] UFL: CharToStr [or CharToString][char type to string type][see also: ChrAt/Chr] Prompt: MyLang, one-liner, input var vChar (char), output var vText (string). Convert vChar to a string vText. If the language lacks a 'char' type, show '___'. AutoHotkey: ___ C++: std::string [e.g. vText = std::string(1, vChar)] [can use: std::string("") + vChar] C#: Char.ToString [e.g. vText = Char.ToString(vChar)] [also: "" + vChar] Crystal: to_s [e.g. vText = vChar.to_s] [also: "" + vChar] Excel: ___ Excel VBA: ___ Go: ___ [note: there is no 'char' type, e.g. 'a' creates an int32, e.g. rune(97) creates an int32] [also (int to string): vText = string(rune(vOrd))] Java: String.valueOf [e.g. vText = String.valueOf(vChar)] [also: Character.toString(vChar)] [also: "" + vChar] JavaScript: ___ Kotlin: toString [e.g. vText = vChar.toString()] [also: Character.toString(vChar)] [also: "" + vChar] [also: String(charArrayOf(vChar))] PHP: ___ Python: ___ R: ___ Ruby: ___ Rust: to_string [e.g. vText = vChar.to_string()] [also: String::from(vChar)] [also: format!("{}", vChar)] Scala: toString [e.g. vText = vChar.toString] [also: String.valueOf(vChar)] [also: Character.toString(vChar)] [also: "" + vChar] SQL (MySQL): ___ SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: String [e.g. vText = String(vChar)] UFL: StrToChar [or StringToChar][get first char of string as a char][string type to char type][string to char][see also: Ord/ChrAt] Prompt: MyLang, one-liner, input var vText (string), output var vChar (char). vChar is the first char of vText. If the language lacks a 'char' type, show '___'. AutoHotkey: ___ C++: ___ [can use (UTF-8 byte): vChar = vText[0]] C#: ___ [can use (UTF-16 short): vChar = vText[0]] Crystal: ___ [can use (codepoint): vChar = vText[0]] [also (codepoint): vText.chars[0]] Excel: ___ Excel VBA: ___ Go: ___ [note: there is no 'char' type, e.g. 'a' creates an int32] [can use (codepoint): vOrd := []rune(vText)[0]] Java: charAt [e.g. (UTF-16 short): vChar = vText.charAt(0)] JavaScript: ___ Kotlin: ___ [can use (UTF-16 short): vChar = vText[0]] PHP: ___ Python: ___ R: ___ Ruby: ___ Rust: nth [e.g. (codepoint): vChar = vText.chars().nth(0).unwrap()] [also (UTF-8 byte): vChar = char::from(vText.as_bytes()[0])] Scala: charAt [e.g. (UTF-16 short): vChar = vText.charAt(0)] [also: (UTF-16 short): vChar = vText(0)] SQL (MySQL): ___ SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: ___ [can use (codepoint): vChar = Array(vText)[0]] UFL: CharToInt [char type to int type] Prompt: MyLang, one-liner, input var vChar (char), output var vNum (int). Convert vChar to an int vNum. If the language lacks a 'char' type, show '___'. AutoHotkey: ___ C++: ___ [e.g. vOrd = (int)(unsigned char)vChar] C#: ___ [e.g. vOrd = (int)vChar] Crystal: ord [e.g. vOrd = vChar.ord] Excel: ___ Excel VBA: ___ Go: ___ [note: there is no 'char' type, e.g. 'a' creates an int32] Java: ___ [e.g. vOrd = (int)vChar] JavaScript: ___ Kotlin: code [e.g. vOrd = vChar.code] PHP: ___ Python: ___ R: ___ Ruby: ___ Rust: ___ [e.g. vOrd = vChar as i32] [also: u32::from(vChar) as i32] [also: into] Scala: ___ [e.g. vOrd = vChar.toInt] SQL (MySQL): ___ SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: ___ [e.g. vOrd = vChar.unicodeScalars.first!.value] UFL: IntToChar [or CharNewDemo][int type to char type][WARNING: different languages have different upper bounds e.g. 127/65535/1114111, some use wraparound][see also: StrSurrogatePairDemo] Prompt: MyLang, one-liner, input var vOrd (int), output var vChar (char). Convert vNum to a char vChar. If the language lacks a 'char' type, show '___'. AutoHotkey: ___ C++: char [e.g. (ASCII: codepoints 0-127): vChar = (char)vOrd] [note: UTF-8 bytes, range is -128 to 127] C#: char [e.g. (codepoints 0-65535): vChar = (char)vOrd] Crystal: chr [e.g. (codepoints 0-1114111): vChar = vOrd.chr] Excel: ___ Excel VBA: ___ Go: ___ [note: there is no 'char' type, e.g. 'a' creates an int32] [also (some methods expect a rune) (codepoints 0-1114111): rune(vOrd)] Java: char [e.g. (codepoints 0-65535): vChar = (char)vOrd] JavaScript: ___ Kotlin: toChar [e.g. (codepoints 0-65535): vChar = vOrd.toChar()] PHP: ___ Python: ___ R: ___ Ruby: ___ Rust: char::from_u32 [e.g. (i32 as u32) (codepoints 0-1114111): vChar = char::from_u32(vOrd as u32).unwrap()] [also: char::from_u32_unchecked()] [also: chars 0-255: vOrd as u8 as char] [also: chars 0-255: char::from(vOrd as u8)] [also: try_into()] Scala: toChar [e.g. (codepoints 0-65535): vChar = vOrd.toChar] SQL (MySQL): ___ SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: ___ [e.g. (codepoints 0-1114111): vChar = Character(UnicodeScalar(vOrd)!)] UFL: IsString [or VarIsString/Any.IsString/IsStr/VarIsStr/Any.IsStr][check if variable is of string type][see also: Any.IsTypeDemo] Prompt: MyLang, one-liner, input var vVar (unknown type), output var vBool (bool). Check if vVar is of type string. AutoHotkey: ___ [e.g. vBool := vVar is String] [note: AHK v2 onwards] C++: ___ [e.g. vBool = std::is_same<decltype(vVar),std::string>::value] C#: ___ [e.g. vBool = vVar is String] Crystal: ___ [e.g. vBool = vVar.is_a?(String)] [also: e.g. vVar.is_a? String] Excel: ___ [e.g. =ISTEXT(A1)] [also: =TYPE(A1)=2] Excel VBA: ___ [e.g. vBool = TypeName(vVar) = "String"] [also: VarType(vVar) = vbString] Go: ___ [e.g. vBool := fmt.Sprintf("%T", vVar) == "string"] Java: ___ [e.g. vBool = ((Object)vVar).getClass().equals(String.class)] JavaScript: ___ [e.g. vBool = typeof vVar == "string"] [also (string object): vBool = vVar instanceof String] Kotlin: ___ [e.g. vBool = vVar is String] [also: vVar!!::class.simpleName == "String"] PHP: ___ [e.g. $vBool = is_string($vVar)] [also: gettype($vVar) == "string"] Python: ___ [e.g. vBool = isinstance(vVar, str)] [also: type(vVar) is str] [WARNING: returns False: "abc" is str] R: ___ [e.g. vBool = is.character(vVar)] [also: typeof(vVar) == "character"] Ruby: ___ [e.g. vBool = vVar.is_a?(String)] [also: e.g. vVar.is_a? String] Rust: ___ [e.g. vBool = type_name_of_val(&vVar) == "&str"] [requires: use std::any::type_name_of_val] [also: compare against "alloc::string::String"] Scala: ___ [e.g. vBool = vVar.isInstanceOf[String]] [also: vVar.getClass().getSimpleName() == "String"] SQL (MySQL): ___ [can use (for values): CREATE TEMPORARY TABLE MyTempTable SELECT 123; DESC MyTempTable;] [also (for table columns, note: doesn't work with temporary tables): SELECT data_type FROM information_schema.columns WHERE table_name = 'MyTable'] SQL (PostgreSQL): ___ [note: pg_typeof('abc') returns 'unknown'] SQL (SQLite): ___ [e.g. typeof(MyVar) == 'text'] Swift: ___ [e.g. vBool = vVar is String] UFL: StrLower [make all characters lower case] Prompt: MyLang, one-liner, input var vText (string), output var vTextNew (string). Convert vText to lower-case vTextNew. AutoHotkey: StrLower [e.g. vTextNew := StrLower(vText)] [also: Format("{:L}", vText)] C++: tolower [e.g. (downcases ASCII chars, modifies string): std::transform(vText.begin(), vText.end(), vText.begin(), [](auto c){return std::tolower(c);})] [also (downcases ASCII chars, modifies string, uses global version of tolower): std::transform(vText.begin(), vText.end(), vText.begin(), ::tolower)] [requires (transform): #include <algorithm>] C#: ToLower [e.g. vTextNew = vText.ToLower()] Crystal: downcase [e.g. vTextNew = vText.downcase] Excel: LOWER [e.g. =LOWER(A1)] Excel VBA: LCase [e.g. vTextNew = LCase(vText)] [also: StrConv(vText, vbLowerCase)] Go: strings.ToLower [e.g. vTextNew := strings.ToLower(vText)] Java: toLowerCase [e.g. vTextNew = vText.toLowerCase()] JavaScript: toLowerCase [e.g. vTextNew = vText.toLowerCase()] Kotlin: lowercase [e.g. vTextNew = vText.lowercase()] [defunct: vText.toLowerCase()] PHP: mb_strtolower [e.g. $vTextNew = mb_strtolower($vText)] [WARNING: strtolower modifies ASCII letters only] Python: str.lower [e.g. vTextNew = vText.lower()] R: tolower [e.g. vTextNew = tolower(vText)] Ruby: downcase [e.g. vTextNew = vText.downcase] Rust: to_lowercase [e.g. vTextNew = vText.to_lowercase()] [also: to_ascii_lowercase] Scala: toLowerCase [e.g. vTextNew = vText.toLowerCase] SQL (MySQL): lower [e.g. lower(MyText)] [alias: lcase] SQL (PostgreSQL): lower [e.g. lower(MyText)] SQL (SQLite): lower [e.g. lower(MyText)] [WARNING: only modifies ASCII letters] Swift: lowercased [e.g. vTextNew = vText.lowercased()] UFL: (StrLowerAsciiOnly) [make all ASCII letters lower case (leave other chars unchanged)][see also: StrTranslate] Prompt: MyLang, one-liner, input var vText (string), output var vTextNew (string). Make all ASCII letters lower case (leave other chars unchanged). AutoHotkey: ___ [can use: vTextNew := RegExReplace(vText, "[A-Z]", "$L0")] C++: ___ [can use: std::string vTextNew; std::transform(vText.begin(), vText.end(), std::back_inserter(vTextNew), [](unsigned char c){return (c >= 'A' && c <= 'Z') ? c+32 : c;});] C#: ___ [can use: vTextNew = System.Text.RegularExpressions.Regex.Replace(vText, "[A-Z]", v=>v.Value.ToLower())] Crystal: ___ [can use: vTextNew = vText.gsub(/[A-Z]/, &.downcase)] Excel: ___ Excel VBA: ___ [can use: vTextNew = "": For i = 1 To Len(vText): c = Mid(vText, i, 1): vTextNew = vTextNew & IIf(c Like "[A-Z]", LCase(c), c): Next] Go: ___ [can use: vTextNew := regexp.MustCompile("[A-Z]").ReplaceAllStringFunc(vText, strings.ToLower)] Java: ___ [can use: vTextNew = vText.replaceAll("([A-Z])", "$1").toLowerCase()] [also: vTextNew = vText.chars().map(c -> c >= 'A' && c <= 'Z' ? c+32 : c).collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append).toString()] JavaScript: ___ [can use: vTextNew = vText.replace(/[A-Z]/g, v => v.toLowerCase())] Kotlin: ___ [can use: vTextNew = vText.replace(Regex("[A-Z]")){it.value.lowercase()}] PHP: ___ [can use: $vTextNew = strtolower($vText)] [note: strtolower() only modifies ASCII letters, unlike mb_strtolower()] [also: $vTextNew = preg_replace_callback('/[A-Z]/', fn($m) => strtolower($m[0]), $vText)] Python: ___ [can use: vTextNew = "".join(c.lower() if 'A' <= c <= 'Z' else c for c in vText)] R: ___ [can use: vTextNew = gsub("([A-Z])", "\\L\\1", vText, perl=TRUE)] [note: '\L' requires 'perl=TRUE'] Ruby: ___ [can use: vTextNew = vText.gsub(/[A-Z]/){|v|v.downcase}] [also: vTextNew = vText.gsub(/[A-Z]/, &:downcase.to_proc)] Rust: to_ascii_lowercase [e.g. vTextNew = vText.to_ascii_lowercase()] [also: vTextNew = vText.chars().map(|c|if c.is_ascii_uppercase(){c.to_ascii_lowercase()}else{c}).collect::<String>()] Scala: ___ [can use: vTextNew = vText.map(c => if (c >= 'A' && c <= 'Z') c.toLower else c)] SQL (MySQL): ___ SQL (PostgreSQL): ___ [can use: e.g. translate('CAFÉcafé', 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz')] SQL (SQLite): ___ [can use: e.g. lower('CAFÉcafé')] [note: lower() only modifies ASCII letters] Swift: ___ [can use: vTextNew = vText.map{$0.isASCII && $0.isUppercase ? $0.lowercased() : String($0)}.joined()] UFL: StrUpper [make all characters upper case] Prompt: MyLang, one-liner, input var vText (string), output var vTextNew (string). Convert vText to upper-case vTextNew. AutoHotkey: StrUpper [e.g. vTextNew := StrUpper(vText)] [also: Format("{:U}", vText)] C++: toupper [e.g. (upcases ASCII chars, modifies string): std::transform(vText.begin(), vText.end(), vText.begin(), [](auto c){return std::toupper(c);})] [also (upcases ASCII chars, modifies string, uses global version of toupper): std::transform(vText.begin(), vText.end(), vText.begin(), ::toupper)] [requires (transform): #include <algorithm>] C#: ToUpper [e.g. vTextNew = vText.ToUpper()] Crystal: upcase [e.g. vTextNew = vText.upcase] Excel: UPPER [e.g. =UPPER(A1)] Excel VBA: UCase [e.g. vTextNew = UCase(vText)] [also: StrConv(vText, vbUpperCase)] Go: strings.ToUpper [e.g. vTextNew := strings.ToUpper(vText)] Java: toUpperCase [e.g. vTextNew = vText.toUpperCase()] JavaScript: toUpperCase [e.g. vTextNew = vText.toUpperCase()] Kotlin: uppercase [e.g. vTextNew = vText.uppercase()] [defunct: vText.toUpperCase()] PHP: mb_strtoupper [e.g. $vTextNew = mb_strtoupper($vText)] [WARNING: strtoupper modifies ASCII letters only] Python: str.upper [e.g. vTextNew = vText.upper()] R: toupper [e.g. vTextNew = toupper(vText)] Ruby: upcase [e.g. vTextNew = vText.upcase] Rust: to_uppercase [e.g. vTextNew = vText.to_uppercase()] [also: to_ascii_uppercase] Scala: toUpperCase [e.g. vTextNew = vText.toUpperCase] SQL (MySQL): upper [e.g. upper(MyText)] [alias: ucase] SQL (PostgreSQL): upper [e.g. upper(MyText)] SQL (SQLite): upper [e.g. upper(MyText)] [WARNING: only modifies ASCII letters] Swift: uppercased [e.g. vTextNew = vText.uppercased()] UFL: (StrUpperFirstOnly) [make first char upper case (capitalise it), leave other chars unchanged][see also: StrFirst] Prompt: MyLang, one-liner, input var vText (string), output var vTextNew (string). Upcase the first Unicode char of vText, leave the other Unicode chars unchanged, store as vTextNew. AutoHotkey: ___ [can use (UTF-16 shorts): vTextNew := StrUpper(SubStr(vText, 1, 1)) SubStr(vText, 2)] [also (codepoints): vTextNew := RegExReplace(vText, "^.", "$U0")] C++: ___ [can use (UTF-8 bytes): std::transform with ::toupper, and substr] [also (UTF-8 bytes) (to uppercase 1 byte): vTextNew = (char)std::toupper(vText[0]) + vText.substr(1)] C#: ___ [can use (UTF-16 shorts): vTextNew = vText.Substring(0, 1).ToUpper() + vText.Substring(1)] [also (UTF-16 shorts): vTextNew = vText.Substring(0, 1).ToUpper() + vText.Remove(0, 1)] Crystal: ___ [can use (codepoints): vTextNew = vText[0].upcase + vText[1..]] [WARNING: capitalize makes the 2nd char onwards lower case] Excel: ___ [can use (UTF-16 shorts): =UPPER(LEFT(A1))&MID(A1,2,LEN(A1))] Excel VBA: ___ [can use (UTF-16 shorts): vTextNew = UCase(Left(vText, 1)) & Mid(vText, 2)] Go: ___ [can use (codepoints): vTextNew := strings.ToUpper(string([]rune(vText)[0])) + string([]rune(vText)[1:])] Java: ___ [can use (UTF-16 shorts): vTextNew = vText.substring(0, 1).toUpperCase() + vText.substring(1)] JavaScript: ___ [can use (codepoints): vTextNew = [...vText][0].toUpperCase() + vText.slice([...vText][0].length)] [can use (UTF-16 shorts): vTextNew = vText.charAt().toUpperCase() + vText.slice(1)] Kotlin: ___ [can use (UTF-16 shorts): vTextNew = vText.replaceFirstChar{it.uppercase()}] [can use (UTF-16 shorts): vTextNew = vText.take(1).uppercase() + vText.drop(1)] [deprecated: vText.capitalize()] PHP: ___ [can use (codepoints): $vTextNew = mb_strtoupper(mb_substr($vText, 0, 1)) . mb_substr($vText, 1)] [note: ucfirst only uppercases ASCII chars] Python: capitalize [e.g. (codepoints): vTextNew = vText.capitalize()] [also (codepoints): vTextNew = vText[0].upper() + vText[1:]] R: ___ [can use (codepoints): vTextNew = paste0(toupper(substr(vText, 1, 1)), substring(vText, 2))] [also (codepoints, modify string): substr(vText, 1, 1) = toupper(substr(vText, 1, 1))] Ruby: ___ [can use (codepoints): vTextNew = vText.slice(0).upcase + vText.slice(1..)] [also (codepoints): vTextNew = vText[0].upcase + vText[1..]] [also (codepoints, modify string): vText[0] = vText[0].upcase] [WARNING: capitalize makes the 2nd char onwards lower case] Rust: ___ [can use (codepoints): vTextNew: String = vText.chars().take(1).collect::<String>().to_uppercase() + &vText.chars().skip(1).collect::<String>()] [also: vTextNew = format!("{}{}", vText.chars().next().unwrap().to_uppercase(), vText.chars().skip(1).collect::<String>())] [also (for a mutable string): vTextNew = vText.remove(0).to_uppercase().to_string() + &vText] Scala: capitalize [e.g. (UTF-16 shorts) vText.capitalize] [also (UTF-16 shorts): vTextNew = vText.substring(0, 1).toUpperCase() + vText.substring(1)] SQL (MySQL): ___ [can use: upper(substr(MyText, 1, 1)) || substr(MyText, 2)] [requires (||): set sql_mode=PIPES_AS_CONCAT] SQL (PostgreSQL): ___ [can use: upper(substr(MyText, 1, 1)) || substr(MyText, 2)] SQL (SQLite): ___ [can use: upper(substr(MyText, 1, 1)) || substr(MyText, 2)] Swift: ___ [can use (codepoints): vTextNew = vText.prefix(1).uppercased() + vText.dropFirst()] UFL: (StrUpperAsciiOnly) [make all ASCII letters upper case (leave other chars unchanged)][see also: StrTranslate] Prompt: MyLang, one-liner, input var vText (string), output var vTextNew (string). Make all ASCII letters upper case (leave other chars unchanged). AutoHotkey: ___ [can use: vTextNew := RegExReplace(vText, "[a-z]", "$U0")] C++: ___ [can use: std::string vTextNew; std::transform(vText.begin(), vText.end(), std::back_inserter(vTextNew), [](unsigned char c){return (c >= 'a' && c <= 'z') ? c-32 : c;});] C#: ___ [can use: vTextNew = System.Text.RegularExpressions.Regex.Replace(vText, "[a-z]", v=>v.Value.ToUpper())] Crystal: ___ [can use: vTextNew = vText.gsub(/[a-z]/, &.upcase)] Excel: ___ Excel VBA: ___ [can use: vTextNew = "": For i = 1 To Len(vText): c = Mid(vText, i, 1): vTextNew = vTextNew & IIf(c Like "[a-z]", UCase(c), c): Next] Go: ___ [can use: vTextNew := regexp.MustCompile("[a-z]").ReplaceAllStringFunc(vText, strings.ToUpper)] Java: ___ [can use: vTextNew = vText.replaceAll("([a-z])", "$1").toUpperCase()] [also: vTextNew = vText.chars().map(c -> c >= 'a' && c <= 'z' ? c-32 : c).collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append).toString()] JavaScript: ___ [can use: vTextNew = vText.replace(/[a-z]/g, v => v.toUpperCase())] Kotlin: ___ [can use: vTextNew = vText.replace(Regex("[a-z]")){it.value.uppercase()}] PHP: ___ [can use: $vTextNew = strtoupper($vText)] [note: strtoupper() only modifies ASCII letters, unlike mb_strtoupper()] [also: $vTextNew = preg_replace_callback('/[a-z]/', fn($m) => strtoupper($m[0]), $vText)] Python: ___ [can use: vTextNew = "".join(c.upper() if 'a' <= c <= 'z' else c for c in vText)] R: ___ [can use: vTextNew = gsub("([a-z])", "\\U\\1", vText, perl=TRUE)] [note: '\U' requires 'perl=TRUE'] Ruby: ___ [can use: vTextNew = vText.gsub(/[a-z]/){|v|v.upcase}] [also: vTextNew = vText.gsub(/[a-z]/, &:upcase.to_proc)] Rust: to_ascii_uppercase [e.g. vTextNew = vText.to_ascii_uppercase()] [also: vTextNew = vText.chars().map(|c|if c.is_ascii_lowercase(){c.to_ascii_uppercase()}else{c}).collect::<String>()] Scala: ___ [can use: vTextNew = vText.map(c => if (c >= 'a' && c <= 'z') c.toUpper else c)] SQL (MySQL): ___ SQL (PostgreSQL): ___ [can use: e.g. translate('CAFÉcafé', 'abcdefghijklmnopqrstuvwxyz', 'ABCDEFGHIJKLMNOPQRSTUVWXYZ')] SQL (SQLite): ___ [can use: e.g. upper('CAFÉcafé')] [note: upper() only modifies ASCII letters] Swift: ___ [can use: vTextNew = vText.map{$0.isASCII && $0.isLowercase ? $0.uppercased() : String($0)}.joined()] UFL: StrTitle [set all words to title case][capitalise the first char in each word, and make all other chars lower case][e.g. 'ABC Def ghi' to 'Abc Def Ghi'] Prompt: MyLang, one-liner, input var vText (string), output var vTextNew (string). Convert vText to title-case vTextNew. Capitalise the first char in each word, and make all other chars lower case. AutoHotkey: StrTitle [e.g. vTextNew := StrTitle(vText)] [also: vTextNew := Format("{:T}", vText)] C++: ___ C#: ___ [can use: vTextNew = System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase(vText.ToLower())] [WARNING: ToTitleCase() leaves upper-case words unchanged, modifies all other words (to first char upper, other chars lower)] Crystal: titleize [e.g. vTextNew = vText.titleize] Excel: PROPER [e.g. =PROPER(A1)] Excel VBA: WorksheetFunction.Proper [e.g. vTextNew = WorksheetFunction.Proper(vText)] [also: vTextNew = StrConv(vText, vbProperCase)] Go: ___ [deprecated: vText := strings.Title(strings.ToLower(vText))] [WARNING: strings.Title() capitalises the first letter in each word (leaving other chars unchanged), whereas strings.ToTitle() makes every *char* 'title case' (which often makes every char upper case)] Java: ___ JavaScript: ___ [can use: vTextNew = vText.toLowerCase().replace(/\b\w/g, c => c.toUpperCase())] Kotlin: ___ PHP: mb_convert_case [e.g. $vTextNew = mb_convert_case($vText, MB_CASE_TITLE)] [WARNING (only handles ASCII chars): ucwords(strtolower($vText))] Python: str.title [e.g. vTextNew = vText.title()] R: tools::toTitleCase [e.g. vTextNew = tools::toTitleCase(tolower(vText))] [WARNING: only modifies lower-case words] [WARNING: skips some common English words] [note: tools::toTitleCase() is base R] Ruby: ___ Rust: ___ Scala: ___ SQL (MySQL): ___ SQL (PostgreSQL): initcap [e.g. initcap(MyText)] SQL (SQLite): ___ Swift: capitalized [e.g. vTextNew = vText.capitalized] [requires (capitalized): import Foundation] UFL: (StrUpperFirstOnlyWords) [capitalise the first char in each word, and leave all other chars unchanged][e.g. 'ABC Def ghi' to 'ABC Def Ghi'] Prompt: MyLang, one-liner, input var vText (string), output var vTextNew (string). Capitalise the first char in each word, and leave all other chars unchanged. AutoHotkey: ___ C++: ___ C#: ___ Crystal: ___ Excel: ___ Excel VBA: ___ Go: ___ [deprecated: vText := strings.Title(vText)] [WARNING: strings.Title() capitalises the first letter in each word (leaving other chars unchanged), whereas strings.ToTitle() makes every *char* 'title case' (which often makes every char upper case)] Java: ___ JavaScript: ___ [can use: vTextNew = vText.replace(/\b\w/g, c => c.toUpperCase())] Kotlin: ___ PHP: ___ Python: ___ R: ___ Ruby: ___ Rust: ___ Scala: ___ SQL (MySQL): ___ SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: ___ UFL: StrCompare [or StrCmp][case-sensitive][compares strings and returns 1/0/-1 accordingly (or positive/0/negative)][see also: StrEquals/NumCompare/Array.Sort/StrDiffFirst/SymCharLtEqGt] Prompt: MyLang, one-liner, input vars vText1/vText2 (strings), output var vCmp (int). Do a case-sensitive comparison of strings vText1 and vText2, assign positive/0/negative to vCmp. AutoHotkey: StrCompare [WARNING: case-insensitive by default] [e.g. case-sensitive: vCmp := StrCompare(vText1, vText2, 1)] [note (since AHK v2): < > can't compare strings] C++: compare [e.g. vCmp = vText1.compare(vText2)] [e.g. int vCmp = (int)std::bit_cast<int8_t>(vText1 <=> vText2)] [also: < >] [also: memcmp/strcmp/strncmp/wcscmp/wcsncmp] C#: String.Compare [e.g. vCmp = String.Compare(vText1, vText2)] [also: vCmp = vText1.CompareTo(vText2)] [note: < > can't compare strings] Crystal: compare [e.g. vCmp = vText1.compare(vText2)] [e.g. vText1 <=> vText2] [also: < >] Excel: ___ [WARNING: case-insensitive: < > =] [can use (case-insensitive): =IF(A1<B1,-1,A1>B1)+0] [also (case-sensitive equals): =EXACT(A1,B1)] Excel VBA: StrComp [e.g. vCmp = StrComp(vText1, vText2)] [also: < >] Go: strings.Compare [e.g. vCmp := strings.Compare(vText1, vText2)] [also: cmp.Compare()] [also: < >] Java: compareTo [e.g. vCmp = vText1.compareTo(vText2)] [also: compareToIgnoreCase] [note: < > can't compare strings] JavaScript: ___ [can use: vCmp = +(vText1>vText2)||0-(vText1<vText2)] [also: vCmp = (vText1>vText2)?1:(vText1<vText2)?-1:0] [WARNING: localeCompare() appears to lack a way to do a default string comparison, i.e. no case-sensitive comparison by Unicode codepoints] [note: '0-', not '-', to prevent negative zeros (swapping the clauses would also work)] [also: < >] Kotlin: compareTo [e.g. vCmp = vText1.compareTo(vText2)] [also: < >] PHP: substr_compare [e.g. case-sensitive: $vCmp = substr_compare($vText1, $vText2, 0)] [e.g. case-insensitive: substr_compare($vText1, $vText2, 0, null, true)] [WARNING: avoid comparison operators such as < > <=> because they compare numeric-looking strings numerically e.g. ("aa" < "b") returns true but ("11" < "2") returns false] Python: ___ [can use: vCmp = +(vText1>vText2) or -(vText1<vText2)] [also: < >] R: ___ [can use (locale comparison): vCmp = (if (vText1<vText2) -1 else +(vText1>vText2))] [also (locale comparison): < >] [WARNING: R uses the locale for string comparison, e.g. for locale 'en_US.UTF-8', ("ABC" > "abc") returns TRUE, which is unusual, for a case-sensitive Unicode codepoint comparison, that returns FALSE] [note: for a more standard comparison, use locale 'C', e.g. Sys.setlocale("LC_COLLATE", "C")] Ruby: ___ [e.g. vCmp = vText1 <=> vText2] [also: < >] [also (case-insensitive): casecmp] Rust: cmp [e.g. vCmp = vText1.cmp(vText2) as i32] [also: < >] Scala: compare [e.g. vCmp = vText1.compare(vText2)] [also: vText1.compareTo(vText2)] [also: compareToIgnoreCase] [also: < >] SQL (MySQL): strcmp [e.g. strcmp(MyText1, MyText2 COLLATE utf8mb4_bin)] [WARNING: case-insensitive by default] SQL (PostgreSQL): ___ [can use: (CASE WHEN MyText1<MyText2 COLLATE "C" THEN -1 ELSE (MyText1>MyText2 COLLATE "C")::int END)] SQL (SQLite): ___ [can use: iif(MyText1<MyText2,-1,MyText1>MyText2)] Swift: compare [e.g. vCmp = vText1.compare(vText2).rawValue] [also: < >] [requires (compare): import Foundation] UFL: StrCompareCasIns [case-insensitive][compares strings and returns 1/0/-1 accordingly (or positive/0/negative)][see also: StrEquals/NumCompare/Array.Sort/StrDiffFirst] Prompt: MyLang, one-liner, input vars vText1/vText2 (strings), output var vCmp (int). Do a case-sensitive comparison of strings vText1 and vText2, assign positive/0/negative to vCmp. AutoHotkey: StrCompare [WARNING: case-insensitive by default] [e.g. case-insensitive: StrCompare(vText1, vText2)] [note (since AHK v2): < > can't compare strings] C++: ___ C#: String.Compare [e.g. String.Compare(vText1, vText2, StringComparison.OrdinalIgnoreCase)] [note: < > can't compare strings] Crystal: compare [e.g. case-insensitive: vText1.compare(vText2, true)] Excel: ___ [can use (case-insensitive): < > =] Excel VBA: StrComp [e.g. StrComp(vText1, vText2, 1)] Go: ___ [can use (case-insensitive equals): strings.EqualFold(vText1, vText2)] Java: compareToIgnoreCase [e.g. vText1.compareToIgnoreCase(vText2)] [note: < > can't compare strings] JavaScript: localeCompare [e.g. vText1.localeCompare(vText2, undefined, {sensitivity:"accent"})] Kotlin: ___ PHP: strcasecmp [e.g. case-insensitive: strcasecmp($vText1, $vText2)] [e.g. case-insensitive: substr_compare($vText1, $vText2, 0)] [WARNING (substr_compare): case-insensitive by default] [WARNING (strcasecmp/substr_compare): only ASCII chars are compared case-insensitively, other chars are compared case-sensitively] Python: ___ R: ___ Ruby: casecmp [e.g. case-insensitive: vText1.casecmp(vText2)] Rust: ___ Scala: compareToIgnoreCase [e.g. vText1.compareToIgnoreCase(vText2)] [can use: < >] SQL (MySQL): strcmp [e.g. strcmp(MyText1, MyText2)] [can use: strcmp(MyText1, MyText2 COLLATE utf8mb4_0900_as_ci)] [note: 'as': accent-sensitive] SQL (PostgreSQL): ___ [can use: (CASE WHEN lower(MyText1)<lower(MyText2) COLLATE "C" THEN -1 ELSE (lower(MyText1)>lower(MyText2) COLLATE "C")::int END)] [WARNING: 'MyText1 > MyText2' may give an unintuitive result depending on the default collation] SQL (SQLite): ___ [can use: iif(lower(MyText1)<lower(MyText2),-1,lower(MyText1)>lower(MyText2))] Swift: caseInsensitiveCompare [e.g. vText1.caseInsensitiveCompare(vText2)] [also: vText1.compare(vText2, options:.caseInsensitive)] [requires (caseInsensitiveCompare/compare): import Foundation] UFL: (StrEqualsContainsStartsEndsFuncs) [list the function/method names for StrEquals/StrContains/StrStarts/StrEnds equivalents, if available][see also: StrEquals/StrContains/StrStarts/StrEnds/TrimBothLeftRightFuncs/IsNaNFiniteInfiniteFuncs/Array.AllAnyNoneMethods] Prompt: MyLang. For strings, slash-separated, list the methods/functions (ignore operators) for: string equals/string contains/string starts with/string ends with, use '___' if no built-in method/function exists. AutoHotkey: ___/InStr/___/___ C++: ___/___/starts_with/ends_with C#: String.Equals/Contains/StartsWith/EndsWith Crystal: ___/includes/starts_with/ends_with Excel: EXACT/___/___/___ Excel VBA: ___/InStr/___/___ Go: ___/strings.Contains/strings.HasPrefix/strings.HasSuffix Java: equals/contains/startsWith/endsWith JavaScript: ___/includes/startsWith/endsWith Kotlin: equals/contains/startsWith/endsWith PHP: ___/str_contains/str_starts_with/str_ends_with Python: operator.eq/in/str.startswith/str.endswith R: ___/___/startsWith/endsWith Ruby: eql/include/start_with/end_with Rust: eq/contains/starts_with/ends_with Scala: equals/contains/startsWith/endsWith SQL (MySQL): ___/instr/___/___ SQL (PostgreSQL): ___/___/starts_with/___ SQL (SQLite): ___/instr/___/___ Swift: elementsEqual/contains/hasPrefix/hasSuffix UFL: StrEquals [are two strings equal, case-sensitive][see also: StrCompare/StrContains/StrStarts/StrEnds] Prompt: MyLang, one-liner, input vars vText1/vText2 (strings), output var vIsMatch (bool). Check if vText1/vText2 are case-sensitive equal, assign to vIsMatch. AutoHotkey: ___ [can use: ==] [note: case-insensitive: =] [e.g. vIsMatch := (vText1 == vText2)] C++: ___ [can use: ==] [e.g. vIsMatch = (vText1 == vText2)] C#: String.Equals [e.g. vIsMatch = String.Equals(vText1, vText2)] [can use: ==] Crystal: ___ [can use: ==] [also: vText1.compare(vText2).zero?] [e.g. vIsMatch = (vText1 == vText2)] Excel: EXACT [can use (case-insensitive): =] [e.g. =EXACT(A1,B1)] Excel VBA: ___ [can use: =] [WARNING: = is case-sensitive in Excel VBA, but case-insensitive in Excel sheet formulas] [e.g. vIsMatch = (vText1 = vText2)] Go: ___ [can use: ==] [e.g. vIsMatch := (vText1 == vText2)] Java: equals [e.g. vIsMatch = vText1.equals(vText2)] [MAJOR WARNING: avoid ==, == compares references, equals() compares values, it just happens that very often 2 strings of equal value are given the same reference] [also: equalsIgnoreCase()] [e.g. false: "aa".split("")[0] == "a"] [e.g. true: "aa".split("")[0].equals("a")] [e.g. false: "a" == "A".toLowerCase()] JavaScript: ___ [can use: ===] [also: ==] [e.g. vIsMatch = (vText1 === vText2)] Kotlin: equals [e.g. vIsMatch = vText1.equals(vText2)] [can use: ==] PHP: ___ [can use: ==] [e.g. $vIsMatch = ($vText1 == $vText2)] Python: operator.eq [can use: ==] [requires: import operator] [e.g. vIsMatch = (vText1 == vText2)] [e.g. vIsMatch = operator.eq(vText1, vText2)] R: ___ [can use: ==] [also: vIsMatch = identical(vText1, vText2)] [e.g. vIsMatch = (vText1 == vText2)] Ruby: eql [e.g. vIsMatch = vText1.eql?(vText2)] [can use: ==] [also (case-insensitive, returns bool): vText1.casecmp?(vText2)] Rust: eq [e.g. vIsMatch = vText1.eq(vText2)] [can use: ==] [also: eq_ignore_ascii_case] Scala: equals [e.g. vIsMatch = vText1.equals(vText2)] [can use: ==] [also: equalsIgnoreCase] SQL (MySQL): ___ [can use (if both strings): MyText1 = BINARY MyText2] [also (cast to string before compare): '' || MyText1 = BINARY '' || MyText2] [also: MyText1 = MyText2 COLLATE utf8mb4_bin] [WARNING: '=' is case-insensitive] [requires (||): set sql_mode=PIPES_AS_CONCAT] SQL (PostgreSQL): ___ [can use (if both strings): MyText1 = MyText2] [also (cast to string before compare): '' || MyText1 = '' || MyText2] SQL (SQLite): ___ [can use (if both strings): MyText1 == MyText2] [also (cast to string before compare): '' || MyText1 == '' || MyText2] Swift: elementsEqual [e.g. vIsMatch = vText1.elementsEqual(vText2)] [can use: ==] UFL: StrEqualsCasIns [are two strings equal, case-insensitive][see also: StrCompare/StrContains/StrStarts/StrEnds] Prompt: MyLang, one-liner, input vars vText1/vText2 (strings), output var vIsMatch (bool). Check if vText1/vText2 are case-insensitive (accent-sensitive) equal, assign to vIsMatch. AutoHotkey: ___ [can use (case-insensitive): =] [also (case-insensitive): vIsMatch := !StrCompare(vText1, vText2)] [e.g. vIsMatch := (vText1 = vText2)] C++: ___ C#: String.Equals [e.g. vIsMatch = String.Equals(vText1, vText2, StringComparison.OrdinalIgnoreCase)] Crystal: compare [e.g. case-insensitive: vIsMatch = vText1.compare(vText2, true).zero?] Excel: ___ [can use (case-insensitive): =] [e.g. =A1=B1] Excel VBA: ___ [can use: vIsMatch = (StrComp(vText1, vText2, 1) = 0)] Go: strings.EqualFold [e.g. vIsMatch := strings.EqualFold(vText1, vText2)] Java: equalsIgnoreCase [e.g. vIsMatch = vText1.equalsIgnoreCase(vText2)] JavaScript: ___ [can use: vIsMatch = (vText1.toLowerCase() == vText2.toLowerCase())] [also: vIsMatch = !vText1.localeCompare(vText2, undefined, {sensitivity:"accent"})] Kotlin: equals [e.g. vIsMatch = vText1.equals(vText2, ignoreCase = true)] PHP: ___ [can use (case-insensitive): $vIsMatch = !strcasecmp($vText1, $vText2)] [also (case-insensitive): $vIsMatch = !substr_compare($vText1, $vText2, 0)] [WARNING (strcasecmp/substr_compare): only ASCII chars are compared case-insensitively, other chars are compared case-sensitively] Python: ___ R: ___ Ruby: casecmp [e.g. case-insensitive, returns bool: vIsMatch = vText1.casecmp?(vText2)] Rust: ___ [can use: vIsMatch = vText1.eq_ignore_ascii_case(vText2)] Scala: equalsIgnoreCase [e.g. vIsMatch = vText1.equalsIgnoreCase(vText2)] SQL (MySQL): ___ [can use: MyText1 = MyText2] [also (where 'lower' is unnecessary since '=' is case-insensitive): lower(MyText1) = lower(MyText2)] [WARNING: '=' is case-insensitive] SQL (PostgreSQL): ___ [can use: lower(MyText1) = lower(MyText2)] SQL (SQLite): ___ [can use: lower(MyText1) == lower(MyText2)] [also: MyText1 == MyText2 COLLATE NOCASE] Swift: ___ [can use: vIsMatch = (vText1.caseInsensitiveCompare(vText2).rawValue == 0)] [requires: import Foundation] UFL: (StrClamp) [clamp a string (inclusive end)][clamp: if input below min, return min, else if above max, return max, else return input][equivalent to obtaining the median of 3 strings][see also: StrBetween/Clamp/StrCompare] Prompt: MyLang, one-liner, input vars vText/vMin/vMax (strings), output var vTextNew (string). If vText < vMin, return vMin, else if vText > vMax, return vMax, else return vText, assign to vTextNew. Use case-sensitive comparison based on Unicode codepoints. AutoHotkey: ___ C++: std::clamp [e.g. vTextNew = std::clamp(vText, vMin, vMax)] C#: ___ Crystal: ___ Excel: ___ Excel VBA: ___ Go: ___ Java: ___ JavaScript: ___ [can use: vTextNew = (vText < vMin) ? vMin : (vText > vMax) ? vMax : vText] Kotlin: ___ PHP: ___ Python: ___ R: ___ [can use (median): vTextNew = median(c(vText, vMin, vMax))] Ruby: ___ Rust: clamp [e.g. vTextNew = vText.clamp(vMin, vMax)] Scala: ___ [can use (median): vTextNew = Array(vText, vMin, vMax).sorted.toList(1)] SQL (MySQL): ___ [can use: greatest(MyMin, least(MyText, MyMax COLLATE utf8mb4_bin) COLLATE utf8mb4_bin)] SQL (PostgreSQL): ___ [can use: greatest(MyMin, least(MyText, MyMax))] SQL (SQLite): ___ [can use: max(MyMin, min(MyText, MyMax))] Swift: ___ UFL: (StrBetween) [is string between two values][inclusive to inclusive][return if string is between min/max][see also: Between/StrClamp/StrCompare] Prompt: MyLang, one-liner, input vars vText/vMin/vMax (strings), output var vTextNew (string). If vMin <= vText, and, vText <= vMax, return true, else return false, assign to vIsMatch. Use case-sensitive comparison based on Unicode codepoints. AutoHotkey: ___ C++: ___ [can use: vIsMatch = std::clamp(vText, vMin, vMax) == vText] C#: ___ Crystal: ___ [can use: vIsMatch = (vMin..vMax) === vText] [also: (vMin..vMax).includes?(vText)] Excel: ___ Excel VBA: ___ Go: ___ Java: ___ JavaScript: ___ [can use: vIsMatch = (vMin <= vText) && (vText <= vMax)] Kotlin: contains [e.g. vIsMatch = (vMin..vMax).contains(vText)] PHP: ___ Python: ___ R: ___ [can use (median): vIsMatch = median(c(vText, vMin, vMax)) == vText] Ruby: between [e.g. vIsMatch = vText.between?(vMin, vMax)] [also: (vMin..vMax) === vText] [also: (vMin..vMax).cover?(vText)] [also (if strings same length): (vMin..vMax).include?(vText)] Rust: ___ [can use: vIsMatch = vText.clamp(vMin, vMax) == vText] Scala: ___ SQL (MySQL): ___ [can use (BETWEEN operator): (MyText BETWEEN MyMin AND MyMax COLLATE utf8mb4_bin)] SQL (PostgreSQL): ___ [can use (BETWEEN operator): (MyText BETWEEN MyMin AND MyMax)] SQL (SQLite): ___ [can use (BETWEEN operator): (MyText BETWEEN MyMin AND MyMax)] Swift: contains [e.g. vIsMatch = (vMin...vMax).contains(vText)] [also: vIsMatch = (vMin...vMax ~= vText)] UFL: (StrBetweenUntil) [is string between two values][inclusive to exclusive][return if string is between min/max][see also: BetweenUntil/StrClamp/StrCompare] Prompt: MyLang, one-liner, input vars vText/vMin/vMax (strings), output var vTextNew (string). If vMin <= vText, and, vText < vMax, return true, else return false, assign to vIsMatch. Use case-sensitive comparison based on Unicode codepoints. AutoHotkey: ___ C++: ___ C#: ___ Crystal: ___ [can use: vIsMatch = (vMin...vMax) === vText] [also: (vMin...vMax).includes?(vText)] Excel: ___ Excel VBA: ___ Go: ___ Java: ___ JavaScript: ___ [can use: vIsMatch = (vMin <= vText) && (vText < vMax)] Kotlin: contains [e.g. vIsMatch = (vMin..<vMax).contains(vText)] PHP: ___ Python: ___ R: ___ Ruby: ___ [can use: vIsMatch = (vMin...vMax) === vText] [also: (vMin...vMax).cover?(vText)] [also (if strings same length): (vMin...vMax).include?(vText)] Rust: ___ Scala: ___ SQL (MySQL): ___ [can use: (MyMin <= MyText COLLATE utf8mb4_bin AND MyText < MyMax COLLATE utf8mb4_bin)] SQL (PostgreSQL): ___ [can use: (MyMin <= MyText AND MyText < MyMax)] SQL (SQLite): ___ [can use: (MyMin <= MyText AND MyText < MyMax)] Swift: contains [e.g. vIsMatch = (vMin..<vMax).contains(vText)] [also: vIsMatch = (vMin..<vMax ~= vText)] UFL: Chr [or Char/IntToStrChar/IntToCharStr/IntToStringChar/IntToCharAsString/IntToCharToStr/IntToChrToStr][codepoint to character (as a string)][i.e. int to char to string][WARNING: different languages have different upper bounds e.g. 127/65535/1114111, some use wraparound][see also: IntToChar/IntToStrCharEscapeDemo/StrSurrogatePairDemo] Prompt: MyLang, one-liner, input var vOrd (int), output var vText (string). Convert codepoint vOrd to a Unicode character, store as vText. AutoHotkey: Chr [e.g. (codepoints 0-1114111): vText := Chr(vOrd)] [also (codepoints 0-65535): Format("{:c}", vOrd)] [defunct: AHK v1: Chr(0) returns ""] C++: ___ [e.g. (ASCII: codepoints 0-127): std::string vText{(char)vOrd}] [e.g. treble clef: std::string vText{(char)240,(char)157,(char)132,(char)158}] [note: std::string stores strings as bytes (UTF-8)] [e.g. (std::string){(char)vOrd}] [also (ASCII: codepoints 0-127): std::string("") + (char)vOrd] [note: UTF-8 bytes, range is -128 to 127] [also: auto vText = (std::string){(char)vOrd}] C#: ConvertFromUtf32 [e.g. (codepoints 0-1114111): vText = Char.ConvertFromUtf32(vOrd)] [also (codepoints 0-65535): "" + (char)vOrd] Crystal: chr [e.g. (codepoints 0-1114111): vText = vOrd.chr.to_s] [also (codepoints 0-1114111): "" + vOrd.chr] Excel: UNICHAR [e.g. (codepoints 0-1114111): =UNICHAR(A1)] [version: Excel 2013: UNICHAR()] [WARNING: CHAR() only handles codepoints 0-127 (ASCII) reliably] Excel VBA: ChrW [e.g. (codepoints 0-65535): vText = ChrW(vOrd)] [e.g. treble clef: ChrW(55348) & ChrW(56606)] Go: string [e.g. (codepoints 0-1114111): vText := string(rune(vOrd))] [WARNING: e.g. string(97) returns string 'a' not string '97'] [note: Go vet warns if 'string(vOrd)' is used, use 'string(rune(vOrd))' instead] Java: ___ [can use (codepoints 0-1114111): vText = new String(new int[]{vOrd}, 0, 1)] [also (codepoints 0-1114111): Character.toString(vOrd)] [also (codepoints 0-1114111): new String(Character.toChars(vOrd))] [also (codepoints 0-65535): "" + (char)vOrd] JavaScript: String.fromCodePoint [e.g. (codepoints 0-1114111): vText = String.fromCodePoint(vOrd)] [also: String.fromCharCode(), e.g. treble clef: String.fromCharCode(55348, 56606)] Kotlin: toString [e.g. (codepoints 0-1114111): vText = Character.toString(vOrd)] [also (codepoints 0-65535): "" + vOrd.toChar()] PHP: mb_chr [e.g. (codepoints 0-1114111): $vText = mb_chr($vOrd)] [WARNING: chr only handles codepoints 0-255] Python: chr [e.g. (codepoints 0-1114111): vText = chr(vOrd)] R: intToUtf8 [e.g. (codepoints 0-1114111): vText = intToUtf8(vOrd)] [note: if passed a vector, returns a multi-char string] Ruby: chr [e.g. (codepoints 0-1114111): vText = vOrd.chr(Encoding::UTF_8)] [also (ASCII: codepoints 0-127): "" + vOrd.chr] [WARNING: a string's encoding affects how p prints it, e.g. US-ASCII: 1.chr prints "\x01", e.g. UTF-8: "" + 1.chr / 1.chr(Encoding::UTF_8) / "\x01" / "\u0001" print "\u0001"] [note: get encoding: vText.encoding] [note: set encoding: e.g. vText.encode("utf-8")] [note: encodings: "" is UTF-8, vNum.chr is US-ASCII, "" + vNum.chr is UTF-8] Rust: ___ [can use (i32 as u32) (codepoints 0-1114111): vText = char::from_u32(vOrd as u32).unwrap().to_string()] Scala: ___ [can use (codepoints 0-1114111): vText = String(Array(vOrd), 0, 1)] [also (codepoints 0-1114111): Character.toString(vOrd)] [also (codepoints 0-1114111): String(Character.toChars(vOrd))] [also (codepoints 0-65535): vOrd.toChar.toString] [also (codepoints 0-65535): "" + vOrd.toChar] SQL (MySQL): char [e.g. char(MyOrd)] SQL (PostgreSQL): chr [e.g. chr(MyOrd)] [also (for '\' followed by one of '0-9A-Fa-f+uU'): unistr(MyOrd), e.g. unistr('\221A\+01D11E\u221A\U0001D11E')] SQL (SQLite): char [e.g. char(MyOrd)] [also (for '\' followed by one of '0-9A-Fa-f+uU'): unistr(MyOrd), e.g. unistr('\221A\+01D11E\u221A\U0001D11E')] Swift: ___ [can use (codepoints 0-1114111): vText = String(UnicodeScalar(vOrd)!)] UFL: ChrMult [multiple codepoints to characters (as a string)][codepoints to string] Prompt: MyLang, one-liner, input vars vOrd1/vOrd2/vOrd3 (ints), output var vText (string). Convert codepoints vOrd1/vOrd2/vOrd3 to Unicode characters, concatenate as vText. AutoHotkey: ___ [can use (codepoints 0-65535): vText := Format("{:c}{:c}{:c}", vOrd1, vOrd2, vOrd3)] [also (codepoints 0-1114111): Chr(vOrd1) Chr(vOrd2) Chr(vOrd3)] C++: ___ [can use (UTF-8 bytes): std::string vText{(char)vOrd1, (char)vOrd2, (char)vOrd3}] C#: ___ [can use: vText = String.Concat(new int[]{vOrd1, vOrd2, vOrd3}.Select(v=>(char)v))] [requires (Select): using System.Linq] Crystal: ___ [can use: vText = [vOrd1, vOrd2, vOrd3].map(&.chr).join] [also: printf("%c%c%c", vOrd1.chr, vOrd2.chr, vOrd3.chr)] Excel: ___ Excel VBA: ___ Go: ___ [can use: vText := fmt.Sprintf("%c%c%c", vOrd1, vOrd2, vOrd3)] Java: ___ [can use: vText = new String(new int[]{vOrd1, vOrd2, vOrd3}, 0, vCount)] JavaScript: String.fromCodePoint [e.g. vText = String.fromCodePoint(vOrd1, vOrd2, vOrd3)] Kotlin: ___ [can use: vText = String.format("%c%c%c", vOrd1, vOrd2, vOrd3)] [also: arrayOf(vOrd1, vOrd2, vOrd3).map{it.toChar()}.joinToString("")] PHP: ___ [can use: vText = sprintf("%c%c%c", vOrd1, vOrd2, vOrd3)] Python: ___ [can use: vText = "{:c}{:c}{:c}".format(vOrd1, vOrd2, vOrd3)] R: intToUtf8 [e.g. vText = intToUtf8(c(vOrd1, vOrd2, vOrd3))] Ruby: ___ [can use: vText = sprintf("%c%c%c", vOrd1, vOrd2, vOrd3)] Rust: ___ [can use: vText = [vOrd1, vOrd2, vOrd3].into_iter().map(char::from).collect::<String>()] Scala: ___ [can use: vText = String(Array(vOrd1, vOrd2, vOrd3), 0, vCount)] SQL (MySQL): char [e.g. char(MyOrd1, MyOrd2, MyOrd3)] SQL (PostgreSQL): ___ [can use: chr(MyOrd1) || chr(MyOrd2) || chr(MyOrd3)] SQL (SQLite): char [e.g. char(MyOrd1, MyOrd2, MyOrd3)] Swift: ___ [can use: vText = String(format:"%c%c%c", vOrd1, vOrd2, vOrd3)] [requires: import Foundation] UFL: ChrRange [codepoint range (inclusive end) to characters, concatenated to form a string][see also: Range.MapBlockDemo/Range.ToArray] Prompt: MyLang, one-liner, input vars vOrd1/vOrd2 (ints), output var vText (string). vText equals chars vOrd1 to vOrd2 inclusive. AutoHotkey: ___ C++: ___ [can use (ASCII): std::string vText; for(int i=vOrd1; i<=vOrd2; ++i) vText += (char)i;] C#: ___ [can use: vText = string.Concat(Enumerable.Range(vOrd1, vOrd2-vOrd1+1).Select(i=>(char)i))] [WARNING (Enumerable.Range): 2nd param is count, not end] Crystal: ___ [can use: vText = (vOrd1..vOrd2).map(&.chr).join] Excel: ___ Excel VBA: ___ [can use: vText = "": For i = vOrd1 To vOrd2: vText = vText & Chr(i): Next] Go: ___ Java: ___ [can use: vText = IntStream.rangeClosed(vOrd1, vOrd2).mapToObj(i->String.valueOf((char)i)).collect(Collectors.joining())] JavaScript: ___ [can use: vText = String.fromCodePoint(...Array.from({length:vOrd2-vOrd1+1}, (_,i)=>vOrd1+i))] [also: vText = Array.from({length:vOrd2-vOrd1+1}, (_,i)=>String.fromCodePoint(vOrd1+i)).join("")] Kotlin: ___ [can use: vText = (vOrd1..vOrd2).map{it.toChar()}.joinToString("")] PHP: ___ [can use: $vText = implode("", array_map("mb_chr", range($vOrd1, $vOrd2)))] Python: ___ [can use: vText = "".join(chr(i) for i in range(vOrd1, vOrd2+1))] [also: vText = "".join(map(lambda i:chr(i), range(vOrd1, vOrd2+1)))] R: intToUtf8 [e.g. vText = intToUtf8(vOrd1:vOrd2)] [also (ASCII): vText = rawToChar(as.raw(vOrd1:vOrd2))] Ruby: ___ [can use: vText = (vOrd1..vOrd2).map(&:chr).join] Rust: ___ [can use: vText = (vOrd1..=vOrd2).map(|i|char::from_u32(i as u32).unwrap()).collect::<String>()] [also: vText = (vOrd1..=vOrd2).filter_map(std::char::from_u32).collect::<String>()] Scala: ___ [can use: vText = (vOrd1 to vOrd2).map(_.toChar).mkString] [also: vText = Range.inclusive(vOrd1, vOrd2).map(_.toChar).mkString] SQL (MySQL): ___ [can use: e.g. SELECT group_concat(char(v) SEPARATOR '') FROM json_table(concat('[',repeat('0,',127-1),'0]'), '$[*]' columns(v FOR ORDINALITY)) t] [also: e.g. WITH RECURSIVE MySeq AS (SELECT 1 AS i UNION ALL SELECT i+1 FROM MySeq WHERE i<127) SELECT group_concat(char(i USING utf8mb4) SEPARATOR '') FROM MySeq] SQL (PostgreSQL): ___ [can use: e.g. SELECT string_agg(chr(i), '') FROM generate_series(1, 127) AS i] SQL (SQLite): ___ [can use: e.g. SELECT group_concat(char(value), '') FROM generate_series(1, 127)] [also: e.g. WITH RECURSIVE MySeq(i) AS (VALUES(1) UNION ALL SELECT i+1 FROM MySeq WHERE i<127) SELECT group_concat(char(i), '') FROM MySeq] Swift: ___ [can use: vText = String((vOrd1...vOrd2).map{UnicodeScalar($0)!}.map{Character($0)})] [also: vText = String((vOrd1...vOrd2).compactMap{UnicodeScalar($0)}.map{Character($0)})] [also: vText = String(String.UnicodeScalarView((vOrd1...vOrd2).compactMap{UnicodeScalar($0)}))] UFL: (IntToStrCharEscapeDemo) [or IntToStringCharEscapeDemo][e.g. concatenate 3 chars: "√𝄞][see also: Chr/SymEscape/StringNewDemoAscii] Prompt: MyLang, one-liner. 3 literal strings, the escaped hex representations of "\""/"√"/"𝄞", are concatenated. AutoHotkey: ___ [can use: Chr(0x22) Chr(0x221A) Chr(0x1D11E)] [note: implicit string concatenation] [also: Format("{:c}{:c}{:c}{:c}", 0x22, 0x221A, 0xD834, 0xDD1E)] [can use (with RegExMatch/RegExReplace needles): "\x22" "\x{221A}" "\x{1D11E}"] [WARNING: Ord() handles codepoints 0-1114111, whereas '{:c}' only handles codepoints 0-65535] C++: "\u0022" "\u221A" "\U0001D11E" [also (C++23): "\u{1D11E}"] [note: implicit string concatenation] [WARNING: \x has max 255 but consumes as many hex chars as possible] C#: "\u0022" + "\u221A" + "\U0001D11E" [also: "\x0022" + "\x221A"] Crystal: "\x22" + "\u221A" + "\u{1D11E}" [also: "\u{22 221A 1D11E}"] Excel: ___ [can use: =CHAR(HEX2DEC("22"))&UNICHAR(HEX2DEC("221A"))&UNICHAR(HEX2DEC("1D11E"))] Excel VBA: ___ [can use: ChrW(&H22) & ChrW(&H221A) & ChrW(&HD834) & ChrW(&HDD1E)] Go: "\x22" + "\u221A" + "\U0001D11E" Java: "\u005C\u0022" + "\u221A" + "\uD834\uDD1E" [MAJOR WARNING: Java replaces escaped chars, including in comments, before parsing the source code] [note: '\u005C\u0022' resolves to '\"'] [note: no \x] [e.g. vText = \u0022hello\u0022 resolves to vText = "hello"] JavaScript: "\x22" + "\u221A" + "\u{1D11E}" [also: "\u{1D11E}" is equivalent to "\uD834\uDD1E", note: '1D*1*1E' versus 'D*D*1E'] Kotlin: "\u0022" + "\u221A" + "\uD834\uDD1E" [note: no \x] PHP: "\x22" . "\u{221A}" . "\u{1D11E}" Python: "\x22" + "\u221A" + "\U0001D11E" [also (implicit string concatenation): "\x22" "\u221A" "\U0001D11E"] R: paste0("\x22", "\u221A", "\U{1D11E}") [note: upper-case 'U': "\U{1D11E}" ('\u{}' is limited to max 4 hex chars)] [also: "\U0001D11E"] Ruby: "\x22" + "\u221A" + "\u{1D11E}" [also (implicit string concatenation): "\x22" "\u221A" "\u{1D11E}"] [also: "\u{22 221A 1D11E}"] Rust: "".to_string() + "\x22" + "\u{221A}" + "\u{1D11E}" Scala: "\"" + "\u221A" + "\uD834\uDD1E" [note: '\u0022' within a string causes an error] [note: no \x] SQL (MySQL): x'22' || x'E2889A' || x'F09D849E' [note: UTF-8 raw bytes as hex] [also: char(0x22, 0x221A, 0x1D11E USING utf32)] [requires (||): set sql_mode=PIPES_AS_CONCAT] SQL (PostgreSQL): E'\x22\u221A\U0001D11E' [also: unistr('\u0022\u221A\U0001D11E')] SQL (SQLite): x'22' || x'E2889A' || x'F09D849E' [note: UTF-8 raw bytes as hex] [also: char(0x22, 0x221A, 0x1D11E)] [also: unistr('\u0022\u221A\U0001D11E')] Swift: "\u{22}" + "\u{221A}" + "\u{1D11E}" [note: no \x] UFL: Ord [or StringToInt/StrToInt][codepoint at start of string][i.e. string to char to int][i.e. string to first char to int] Prompt: MyLang, one-liner, input var vText (string). Get the codepoint of the Unicode character at the start of vText, assign to vOrd. AutoHotkey: Ord [e.g. (codepoints 0-1114111): vOrd := Ord(vText)] C++: ___ [e.g. read 1 byte: (int)(unsigned char)vText[0]] [note: cast to int so that std::cout prints chars as integers not symbols] [note: std::string stores strings as bytes (UTF-8)] C#: ConvertToUtf32 [e.g. (codepoints 0-1114111): vOrd = Char.ConvertToUtf32(vText, 0)] Crystal: ord [e.g. (codepoints 0-1114111): vOrd = vText[0].ord] Excel: UNICODE [e.g. (codepoints 0-1114111): =UNICODE(A1)] [version: Excel 2013: UNICODE()] [WARNING: CODE() only handles codepoints 0-127 (ASCII) reliably] Excel VBA: AscW [e.g. (codepoints 0-65535): vOrd = AscW(vText) And 65535] [WARNING: codepoints 32768-65535 return -32768 to -1, i.e. a signed short (Int16) rather than an unsigned short (UInt16), use 'And 65535' (bitwise and) to fix this (to correct negative return values and leave positive values unchanged)] Go: ___ [can use (codepoints 0-1114111): vOrd := []rune(vText)[0]] [also (UTF-8 byte): vText[0]] Java: codePointAt [e.g. (codepoints 0-1114111): vOrd = vText.codePointAt(0)] JavaScript: codePointAt [e.g. (codepoints 0-1114111): vOrd = vText.codePointAt()] [also (codepoints 0-65535): vText.charCodeAt()] Kotlin: codePointAt [e.g. (codepoints 0-1114111): vOrd = vText.codePointAt(0)] [also (codepoints 0-65535): vText.single().code] [WARNING: vText.toInt() does text to *int*, e.g. "123" to 123 (not 49), whereas vChar.toInt() does char to *codepoint*, e.g. '1' to 49 (not 1)] [deprecated: vChar.toInt()] PHP: mb_ord [e.g. (codepoints 0-1114111): $vOrd = mb_ord($vText)] [WARNING: ord only handles codepoints 0-255] Python: ord [e.g. (codepoints 0-1114111): vOrd = ord(vText)] R: utf8ToInt [e.g. (codepoints 0-1114111): vOrd = utf8ToInt(vText)] [note: if a multi-char string, returns a vector] Ruby: ord [e.g. (codepoints 0-1114111): vOrd = vText.ord] Rust: ___ [can use (codepoints 0-1114111): vOrd = u32::from(vText.chars().nth(0).unwrap()) as i32] Scala: codePointAt [e.g. (codepoints 0-1114111): vOrd = vText.codePointAt(0)] SQL (MySQL): ___ [can use (codepoints 0-1114111): ord(convert(MyText USING utf32))] [MAJOR WARNING: ord() applies an unusual formula to the first 3 bytes, which works with UTF-32, but few other encodings] [also: ascii(MyText), gets the codepoint for the first byte] SQL (PostgreSQL): ascii [e.g. (codepoints 0-1114111): ascii(MyText)] [note: handles codepoints 0-1114111 despite the name 'ascii' (which would imply 0-127)] SQL (SQLite): unicode [e.g. (codepoints 0-1114111): unicode(MyText)] Swift: ___ [can use (codepoints 0-1114111): vOrd = Array(vText)[0].unicodeScalars.first!.value] [also (codepoints 0-1114111): Int(UnicodeScalar(String(vText.prefix(1)))!.value)] UFL: ChrAt [or CharAt][nth character (as string) (a substring)][WARNING: languages may use 0-based/1-based string indexes][i.e. string to char to string][see also: SubStr/StrSplitChars] Prompt: MyLang, one-liner, input vars vText/vPos (string/int). Get the Unicode character at the 0-based (or 1-based if appropriate) index vPos of vText, assign to vTextNew. AutoHotkey: ___ [can use (UTF-16 short, 1-based): vTextNew := SubStr(vText, vPos, 1)] [can use (codepoint, 1-based): RegExReplace(vText, "^.{" (vPos-1) "}(.).*$", "$1")] C++: ___ [e.g. (UTF-8 byte): vTextNew = std::string("") + vText[vPos]] C#: ___ [e.g. (UTF-16 short): vTextNew = "" + vText[vPos]] Crystal: ___ [can use (codepoint): vTextNew = vText[vPos].to_s] [also: vText.chars[vPos].to_s] Excel: ___ [can use (UTF-16 short, 1-based): =MID(A1,MyPos,1)] Excel VBA: ___ [can use (UTF-16 short, 1-based): vTextNew = Mid(vText, vPos, 1)] Go: ___ [can use (codepoint): vTextNew := string([]rune(vText)[vPos])] [also (codepoint): strings.Split(vText, "")[vPos]] [also (UTF-8 byte): string(vText[vPos])] Java: charAt [e.g. (UTF-16 short): vTextNew = "" + vText.charAt(vPos)] JavaScript: ___ [can use (codepoint): vTextNew = [...vText][vPos]] [note: 'Strings are iterated by Unicode code points.'] [can use (UTF-16 short): vText.charAt(vPos)] [note (charAt): can omit pos to get the first char] Kotlin: get [e.g. (UTF-16 short): vTextNew = "" + vText.get(vPos)] PHP: ___ [can use (codepoint): $vTextNew = mb_substr($vText, $vPos, 1)] [can use (UTF-8 byte): $vText[$vPos]] [WARNING: strings accept negative indexes relative to end, arrays don't (because PHP arrays are really maps, and negative indexes are valid keys)] Python: ___ [can use (codepoint): vTextNew = vText[vPos]] R: ___ [can use (codepoint): vTextNew = substr(vText, vPos, vPos)] Ruby: ___ [can use (codepoint): vTextNew = vText[vPos]] [also: vText.chars[vPos]] Rust: ___ [can use (codepoint): vTextNew = vText.chars().nth(vPos).unwrap().to_string()] Scala: charAt [e.g. (UTF-16 short): vTextNew = "" + vText.charAt(vPos)] SQL (MySQL): ___ [can use (codepoint, 1-based): substr(MyText, MyPos, 1)] SQL (PostgreSQL): ___ [can use (codepoint, 1-based): substr(MyText, MyPos, 1)] SQL (SQLite): ___ [can use (codepoint, 1-based): substr(MyText, MyPos, 1)] Swift: ___ [can use (codepoint): vTextNew = Array(vText)[vPos]] [can use (codepoint): vText[vText.index(vText.startIndex, offsetBy:vPos)]] UFL: OrdAt [codepoint of nth character][WARNING: languages may use 0-based/1-based string indexes][i.e. string to char to int] Prompt: MyLang, one-liner, input vars vText/vPos (string/int). Get the codepoint for the Unicode character at the 0-based (or 1-based if appropriate) index vPos of vText, assign to vOrd. AutoHotkey: ___ [can use (1-based): vOrd := Ord(SubStr(vText, vPos, 2))] [WARNING: uses UTF-16 shorts, position may be partway through a char (returns low surrogate)] C++: ___ C#: ConvertToUtf32 [e.g. vOrd = Char.ConvertToUtf32(vText, vPos)] [WARNING: uses UTF-16 shorts, position may be partway through a char (throws)] Crystal: codepoint_at [e.g. vOrd = vText.codepoint_at(vPos)] [can use: vText[vPos].ord] [also: vText.codepoints[vPos]] Excel: ___ Excel VBA: ___ Go: ___ [can use: vOrd = []rune(vText)[vPos]] [also (UTF-8 byte): vText[vPos]] Java: codePointAt [e.g. vOrd = vText.codePointAt(vPos)] [WARNING: uses UTF-16 shorts, position may be partway through a char (returns low surrogate)] JavaScript: codePointAt [e.g. (nth codepoint): vOrd = [...vText][vPos].codePointAt(0)] [e.g. (nth UTF-16 short): vOrd = vText.codePointAt(vPos)] [WARNING (codePointAt(vPos)): uses UTF-16 shorts, position may be partway through a char (returns low surrogate)] Kotlin: codePointAt [e.g. vOrd = vText.codePointAt(vPos)] [WARNING: uses UTF-16 shorts, position may be partway through a char (returns low surrogate)] PHP: ___ [can use: $vOrd = mb_ord(mb_substr($vText, $vPos, 1))] [WARNING: ord only handles codepoints 0-255] Python: ___ [can use: vOrd = ord(vText[vPos])] R: ___ [can use (1-based): vOrd = utf8ToInt(substr(vText, vPos, vPos))] Ruby: ___ [can use: vOrd = vText[vPos].ord] [also: vText.codepoints[vPos]] Rust: ___ [can use: vOrd = vText.chars().nth(vPos).unwrap() as i32] Scala: codePointAt [e.g. vOrd = vText.codePointAt(vPos)] [WARNING: uses UTF-16 shorts, if position halfway through a surrogate pair returns low surrogate (if position at start of surrogate pair, returns codepoint)] SQL (MySQL): ___ [can use (1-based): ord(convert(substr(MyText, MyPos, 1) USING utf32))] SQL (PostgreSQL): ___ [can use (1-based): ascii(substr(MyText, MyPos, 1))] SQL (SQLite): ___ [can use (1-based): unicode(substr(MyText, MyPos, 1))] Swift: ___ [can use: vOrd = Array(vText)[vPos].unicodeScalars.first!.value] UFL: StrRept [or StrRepeat][repeat a string n times] Prompt: MyLang, one-liner, input vars vCount/vText (int/string), output var vTextNew (string). Repeat vText vCount times, assign to vTextNew. AutoHotkey: ___ [can use: vTextNew := StrReplace(Format("{:" vCount "}", ""), " ", vText)] [WARNING: Format("{:00}", 0) returns 1 char, not 0 chars: StrReplace(Format("{:0" vCount "}", 0), "0", vText)] C++: ___ [can use (to repeat a character): vTextNew = std::string(vCount, vChar)] [can use: repeated +=] C#: ___ [can use: vTextNew = String.Concat(Enumerable.Repeat(vText, vCount))] [also (slower): (new String('_', vCount)).Replace("_", vText)] [requires (Repeat): using System.Linq] Crystal: ___ [can use (* operator): vTextNew = vText * vCount] [WARNING: mathematical operator used on strings] Excel: REPT [e.g. =REPT(MyText,MyCount)] Excel VBA: WorksheetFunction.Rept [e.g. vTextNew = WorksheetFunction.Rept(vText, vCount)] [also: Replace(Space(vCount), " ", vText)] [also: Replace(String(vCount, " "), " ", vText)] [also (repeat a one-char string): String(vCount, vChar)] Go: strings.Repeat [e.g. vTextNew := strings.Repeat(vText, vCount)] Java: repeat [e.g. vTextNew = vText.repeat(vCount)] JavaScript: repeat [e.g. vTextNew = vText.repeat(vCount)] [also: Array(vCount+1).join(vText)] Kotlin: repeat [e.g. vTextNew = vText.repeat(vCount)] PHP: str_repeat [e.g. $vTextNew = str_repeat($vText, $vCount)] Python: ___ [can use (* operator): vTextNew = vText * vCount] [WARNING: mathematical operator used on strings] R: strrep [e.g. vTextNew = strrep(vText, vCount)] Ruby: ___ [can use (* operator): vTextNew = vText * vCount] [WARNING: mathematical operator used on strings] Rust: repeat [e.g. vTextNew = vText.repeat(vCount)] Scala: repeat [e.g. vTextNew = vText.repeat(vCount)] SQL (MySQL): repeat [e.g. repeat(MyText, MyCount)] [also: space(MyCount)] SQL (PostgreSQL): repeat [e.g. repeat(MyText, MyCount)] SQL (SQLite): ___ [can use: replace(hex(zeroblob(MyCount)), '00', MyText)] [also: replace(format('%.*c', MyCount, ' '), ' ', MyText)] [also: replace(format('%' || MyCount || 's', ''), ' ', MyText)] [deprecated: printf (an alias of format)] Swift: String [e.g. vTextNew = String(repeating:vText, count:vCount)] UFL: StrCount [count occurrences of substring][do not count overlapping strings (unless a bool option is available and set to on)][WARNING: languages may use 0-based/1-based string indexes][see also: StrContains/InStr/InStrNth/StrSplit/RegExCount] Prompt: MyLang, one-liner, input vars vText/vNeedle (strings), output var vCount (int). Count the case-sensitive occurrences of vNeedle in vText, assign to vCount. AutoHotkey: ___ [can use (StrReplace's Count parameter): StrReplace(vText, vNeedle, "", 1, &vCount)] [note: 1 to specify case-sensitive] [WARNING (StrReplace): case-insensitive by default] [also (string split): vCount := StrSplit(vText, vNeedle).Length - 1] C++: ___ [can use: int vCount = 0; for (size_t vPos = vText.find(vNeedle); vPos != std::string::npos; vPos = vText.find(vNeedle, vPos+vNeedle.length())) vCount++;] [also (RegEx): auto oRegEx = std::regex(vNeedle); long vCount = std::distance(std::sregex_iterator(vText.begin(), vText.end(), oRegEx), std::sregex_iterator());] [also (ASCII, count chars): int vCount = std::count(vText.begin(), vText.end(), vChar)] [requires (sregex_iterator): #include <regex>] C#: ___ [can use (string split): vCount = vText.Split(vNeedle).Length - 1] Crystal: ___ [can use: vCount = vText.scan(vNeedle).size] [WARNING: vText.count(vNeedle) counts chars, not substrings] Excel: ___ [can use: =(LEN(A1)-LEN(SUBSTITUTE(A1,B1,"")))/LEN(B1)] [can use (for 1-char needles): =LEN(A1)-LEN(SUBSTITUTE(A1,B1,""))] Excel VBA: ___ [can use: vCount = (Len(vText) - Len(Replace(vText, vNeedle, ""))) / Len(vNeedle)] Go: strings.Count [e.g. vCount := strings.Count(vText, vNeedle)] Java: ___ [can use: vCount = (vText.length() - vText.replace(vNeedle, "").length()) / vNeedle.length()] [WARNING: split() takes a RegEx needle, and omits a trailing blank string, workaround: use endsWith()] JavaScript: ___ [can use (string split): vCount = vText.split(vNeedle).length - 1] Kotlin: ___ [can use (string split): vCount = vText.split(vNeedle).size - 1] PHP: mb_substr_count [e.g. $vCount = mb_substr_count($vText, $vNeedle)] [also (uses bytes, and has offset/length parameters): substr_count] Python: str.count [e.g. vCount = vText.count(vNeedle)] R: gregexpr [e.g. oMatch = gregexpr(vNeedle, vText, fixed=TRUE); vCount = ifelse(oMatch[[1]][1]!=-1, length(oMatch[[1]]), 0)] [WARNING: without 'fixed=TRUE', this does a RegEx search] Ruby: ___ [can use: vCount = vText.scan(vNeedle).count] [WARNING: vText.count(vNeedle) counts chars, not substrings] Rust: ___ [can use: vCount = vText.matches(vNeedle).count()] Scala: ___ [can use: vCount = (vText.length - vText.replace(vNeedle, "").length) / vNeedle.length] [WARNING: split() takes a RegEx needle, and omits a trailing blank string, workaround: use endsWith()] SQL (MySQL): ___ [can use: (length(MyText)-length(replace(MyText,MyNeedle,'')))/length(MyNeedle)] SQL (PostgreSQL): ___ [can use: (length(MyText)-length(replace(MyText,MyNeedle,'')))/length(MyNeedle)] [also: array_length(string_to_array(MyText, MyNeedle), 1) - 1] [also (RegEx needle): regexp_count(MyText, MyNeedle)] SQL (SQLite): ___ [can use: (length(MyText)-length(replace(MyText,MyNeedle,'')))/length(MyNeedle)] Swift: ___ [can use: vCount = (vText.count - vText.replacingOccurrences(of:vNeedle, with:"").count) / vNeedle.count] [requires (replacingOccurrences): import Foundation] [WARNING: split() omits leading/trailing blank strings, workaround: use hasPrefix() and hasSuffix()] UFL: StrCountCasIns [count occurrences of substring][WARNING: languages may use 0-based/1-based string indexes][see also: StrContains/InStr/StrSplit] Prompt: MyLang, one-liner, input vars vText/vNeedle (strings), output var vCount (int). Count the case-insensitive (accent-sensitive) occurrences of vNeedle in vText, assign to vCount. AutoHotkey: ___ [can use (StrReplace's Count parameter): StrReplace(vText, vNeedle, "", 0, &vCount)] [note: 0 to specify case-insensitive] [WARNING (StrReplace): case-insensitive by default] [also (string split): vCount := StrSplit(StrLower(vText), StrLower(vNeedle)).Length - 1] C++: ___ C#: ___ Crystal: ___ [can use: vCount = vText.scan(Regex.new(vNeedle, Regex::CompileOptions::IGNORE_CASE)).size] [WARNING: vText.count(vNeedle) counts chars, not substrings] Excel: ___ Excel VBA: ___ Go: ___ Java: ___ JavaScript: ___ [can use: vCount = vText.toLowerCase().split(vNeedle.toLowerCase()).length - 1 Kotlin: ___ PHP: ___ Python: ___ R: ___ [can use (RegEx needle): oMatch = gregexpr(vNeedleRx, vText, ignore.case=TRUE); vCount = ifelse(oMatch[[1]][1]!=-1, length(oMatch[[1]]), 0)] [WARNING: you cannot use ignore.case=TRUE and fixed=TRUE at the same time] Ruby: ___ [can use: vCount = vText.scan(Regexp.new(vNeedle, "i")).count] [WARNING: vText.count(vNeedle) counts chars, not substrings] Rust: ___ Scala: ___ SQL (MySQL): ___ [can use: (char_length(MyText)-char_length(replace(lower(MyText),lower(MyNeedle),'')))/char_length(MyNeedle)] [note: using char_length instead of length, since for some chars the upper/lower-case forms differ in size (bytes)] SQL (PostgreSQL): ___ [can use: (length(MyText)-length(replace(lower(MyText),lower(MyNeedle),'')))/length(MyNeedle)] [also: array_length(string_to_array(lower(MyText), lower(MyNeedle)), 1) - 1] [also (RegEx needle): regexp_count(MyText, MyNeedle)] SQL (SQLite): ___ [can use: (length(MyText)-length(replace(lower(MyText),lower(MyNeedle),'')))/length(MyNeedle)] Swift: ___ UFL: StrLen [string length][note: using the language's default unit of length] Prompt: MyLang, one-liner, input var vText (string), output var vLen (int). Assign length of vText to vLen, using the language's default unit of length. AutoHotkey: StrLen [e.g. vLen := StrLen(vText)] [unit: UTF-16 shorts] C++: size [e.g. vLen = vText.size()] [also: vText.length()] [also: strlen/wcslen] [unit: UTF-8 bytes] [note: 'Both string::size and string::length are synonyms and return the same value.'] C#: Length [e.g. vLen = vText.Length] [unit: UTF-16 shorts] Crystal: size [e.g. vLen = vText.size] [unit: codepoints] Excel: LEN [e.g. =LEN(A1)] [unit: UTF-16 shorts] Excel VBA: Len [e.g. vLen = Len(vText)] [unit: UTF-16 shorts] Go: len [e.g. vLen := len(vText)] [unit: UTF-8 bytes] Java: length [e.g. vLen = vText.length()] [unit: UTF-16 shorts] [WARNING: vText.length() requires parentheses, unlike oArray.length] JavaScript: length [e.g. vLen = vText.length] [unit: UTF-16 shorts] Kotlin: length [e.g. vLen = vText.length] [also: vText.count()] [unit: UTF-16 shorts] PHP: strlen [e.g. $vLen = strlen($vText)] [unit: UTF-8 bytes] Python: len [e.g. vLen = len(vText)] [unit: codepoints] [note: Python 2 and 3 differ] R: nchar [e.g. vLen = nchar(vText)] [unit: codepoints] Ruby: length [e.g. vLen = vText.length] [also: vText.size] [unit (both): codepoints] Rust: len [e.g. vLen = vText.len()] [unit: UTF-8 bytes] Scala: length [e.g. vLen = vText.length] [also: vText.length()] [unit: UTF-16 shorts] SQL (MySQL): char_length [e.g. char_length(MyText)] [unit: codepoints] [also (bytes): length(MyText)] [alias (char_length): character_length] [alias (length): octet_length] SQL (PostgreSQL): length [e.g. length(MyText)] [unit: codepoints] [also (bytes): octet_length(MyText)] [alias (length): char_length, character_length] [also: length(MyText, 'UTF8')] SQL (SQLite): length [e.g. length(MyText)] [unit: codepoints] [also (bytes): octet_length(MyText)] Swift: count [e.g. vLen = vText.count] [unit: codepoints] UFL: (StrLenDemo) [e.g. square root (a BMP char), e.g. treble clef (a surrogate pair)] Prompt: MyLang, two one-liners. For strings "√" and "𝄞", code to get the string length of the char, using the language's default unit of length. Comma-space-separated. AutoHotkey: StrLen("√"), StrLen("𝄞") [output: 1,2] [unit: UTF-16 shorts] C++: std::string("√").length(), std::string("𝄞").length() [output: 3,4] [unit: UTF-8 bytes] C#: "√".Length, "𝄞".Length [output: 1,2] [unit: UTF-16 shorts] Crystal: "√".size, "𝄞".size [output: 1,1] [unit: codepoints] Excel: √, 𝄞 [output: 1,2] [unit: UTF-16 shorts] Excel VBA: Len(ChrW(8730)), Len(ChrW(55348) & ChrW(56606)) [output: 1,2] [unit: UTF-16 shorts] Go: len("√"), len("𝄞") [output: 3,4] [unit: UTF-8 bytes] Java: "√".length(), "𝄞".length() [output: 1,2] [unit: UTF-16 shorts] JavaScript: "√".length, "𝄞".length [output: 1,2] [unit: UTF-16 shorts] Kotlin: "√".length, "𝄞".length [output: 1,2] [unit: UTF-16 shorts] [note: vText.count(): same results] PHP: strlen("√"), strlen("𝄞") [output: 3,4] [unit: UTF-8 bytes] Python: len("√"), len("𝄞") [output: 1,1] [unit: codepoints] R: nchar("√"), nchar("𝄞") [output: 1,1] [unit: codepoints] Ruby: "√".length, "𝄞".length [output: 1,1] [unit: codepoints] Rust: "√".len(), "𝄞".len() [output: 3,4] [unit: UTF-8 bytes] Scala: "√".length, "𝄞".length [output: 1,2] [unit: UTF-16 shorts] SQL (MySQL): char_length('√'), char_length('𝄞') [output: 1,1] [unit: codepoints] SQL (PostgreSQL): length('√'), length('𝄞') [output: 1,1] [unit: codepoints] SQL (SQLite): length('√'), length('𝄞') [output: 1,1] [unit: codepoints] Swift: "√".count, "𝄞".count [output: 1,1] [unit: codepoints] UFL: StrSizeUtf8 [size of string in bytes (UTF-8 encoded)] Prompt: MyLang, one-liner, input var vText (string), output var vSize (int). Assign the size in bytes of vText as a UTF-8 string to vSize. AutoHotkey: StrPut [e.g. vSize := StrPut(vText, "UTF-8")-1] [note: StrPut returns the size in bytes including a null character] C++: size [can use: vSize = vText.size()] [also: std::string(vText).size()] [also: length()] C#: ___ [can use: vSize = Encoding.UTF8.GetBytes(vText).Length] Crystal: bytesize [e.g. vSize = vText.bytesize] Excel: ___ Excel VBA: ___ Go: len [e.g. vSize := len(vText)] Java: ___ [can use: vSize = vText.getBytes().length] JavaScript: ___ [can use: vSize = new TextEncoder().encode(vText).length] Kotlin: ___ [can use: vSize = vText.toByteArray().size] PHP: strlen [e.g. $vSize = strlen($vText)] Python: ___ [can use: vSize = len(vText.encode("utf-8"))] R: nchar [e.g. vSize = nchar(vText, "bytes")] Ruby: bytesize [e.g. vSize = vText.bytesize] Rust: len [e.g. vSize = vText.len()] Scala: ___ [can use: vSize = vText.getBytes.length] SQL (MySQL): length [e.g. length(MyText)] [alias (length): octet_length] SQL (PostgreSQL): octet_length [e.g. octet_length(MyText)] SQL (SQLite): octet_length [e.g. octet_length(MyText)] [also: length(hex(MyText))/2] Swift: ___ [can use: vSize = vText.utf8.count] UFL: StrLenUtf16 [size of string in (2-byte) shorts (UTF-16 encoded)][note: double this value to get 'StrSizeUtf16', size in bytes] Prompt: MyLang, one-liner, input var vText (string), output var vLen (int). Assign the length in 2-byte shorts of vText as a UTF-16 string to vLen. AutoHotkey: StrLen [e.g. vLen := StrLen(vText)] C++: ___ [can use: int vLen = 0; for (const auto& vChar : vText) vLen += ((vChar&0xC0)!=0x80) + ((vChar&0xF8)==0xF0);] [also: vLen = std::accumulate(vText.begin(), vText.end(), 0, [](int vAcc, int vChar) {return vAcc+((vChar&0xC0)!=0x80)+((vChar&0xF8)==0xF0);})] [requires (accumulate): #include <numeric>] [algorithm: +1 if byte doesn't start with 0b10, +1 if byte doesn't start with 0b11110] C#: Length [e.g. vLen = vText.Length] Crystal: ___ [can use: vLen = vText.encode("UTF16LE").bytesize / 2] [WARNING (encode): 'UTF16' prepends a 2-byte BOM ('UTF16LE' doesn't)] Excel: LEN [e.g. =LEN(A1)] Excel VBA: Len [e.g. vLen = Len(vText)] Go: ___ [can use: vLen := len(utf16.Encode([]rune(vText)))] [requires: import "unicode/utf16"] Java: length [e.g. vLen = vText.length()] [WARNING: vText.length() requires parentheses, unlike oArray.length] JavaScript: length [e.g. vLen = vText.length] Kotlin: length [e.g. vLen = vText.length] [also: vText.count()] PHP: ___ [can use: $vLen = strlen(mb_convert_encoding($vText, "UTF-16"))/2] Python: ___ [can use: vLen = len(vText.encode("utf-16-le"))/2] [WARNING (encode): 'utf-16' prepends a 2-byte BOM ('utf-16-le' doesn't)] R: ___ [can use: vLen = nchar(vText) + sum(utf8ToInt(vText)>0xFFFF)] [also: length(iconv(vText, to="UTF-16LE", toRaw=TRUE)[[1]])/2] [WARNING (iconv): 'UTF-16' prepends a 2-byte BOM ('UTF-16LE' doesn't)] Ruby: ___ [can use: vLen = vText.encode(Encoding::UTF_16LE).bytesize / 2] [WARNING (encode): 'UTF_16' prepends a 2-byte BOM ('UTF_16LE' doesn't)] Rust: ___ [can use: vLen = vText.encode_utf16().count()] Scala: length [e.g. vLen = vText.length] SQL (MySQL): ___ [can use: length(convert(MyText USING utf16)) / 2] SQL (PostgreSQL): ___ [can use: 2*length(MyText) + 2*length(regexp_replace(MyText, '[\u0001-\uffff]', '', 'g'))] SQL (SQLite): ___ Swift: ___ [can use: vLen = vText.utf16.count] UFL: StrLenCodepoints [or StrLenUtf32][note: quadruple this value to get 'StrSizeUtf32', size in bytes] Prompt: MyLang, one-liner, input var vText (string), output var vLen (int). Assign the Unicode character count of vText to vLen. AutoHotkey: ___ [can use: vLen := RegExReplace(vText, "s).",, &vLen)] [note: AHK v1: drop the '&'] C++: ___ [can use: int vLen = 0; for (const auto& vChar : vText) vLen += ((vChar&0xC0)!=0x80);] [also: vLen = std::accumulate(vText.begin(), vText.end(), 0, [](int vAcc, int vChar) {return vAcc+((vChar&0xC0)!=0x80);})] [requires (accumulate): #include <numeric>] [algorithm: +1 if byte doesn't start with 0b10] C#: ___ [can use: vLen = Encoding.UTF32.GetBytes(vText).Length/4] Crystal: size [e.g. vLen = vText.size] Excel: ___ Excel VBA: ___ Go: ___ [can use: vLen := len([]rune(vText))] Java: codePointCount [e.g. vLen = vText.codePointCount(0, vText.length())] JavaScript: ___ [can use: vLen = [...vText].length] [note: 'Strings are iterated by Unicode code points.'] Kotlin: codePointCount [e.g. vLen = vText.codePointCount(0, vText.length)] PHP: ___ [can use: $vLen = strlen(mb_convert_encoding($vText, "UTF-32"))/4] [also: mb_strlen($vText)] Python: ___ [can use: vLen = len(vText)] R: nchar [e.g. vLen = nchar(vText)] Ruby: length [e.g. vLen = vText.length] [also: vText.size] Rust: ___ [can use: vLen = vText.chars().count()] Scala: codePointCount [e.g. vLen = vText.codePointCount(0, vText.length)] SQL (MySQL): char_length [e.g. char_length(MyText)] [alias (char_length): character_length] SQL (PostgreSQL): length [e.g. length(MyText)] SQL (SQLite): length [e.g. length(MyText)] Swift: ___ [can use: vLen = vText.count] UFL: StrGetCapacity [get string capacity][in bytes, unless stated][see also: Array.GetCapacity] Prompt: MyLang, one-liner, input var oSB (string builder object or string), output var vCapacity (int). Get the capacity of oSB in bytes as vCapacity. If not possible, show '___'. AutoHotkey: VarSetStrCapacity [note: in UTF-16 shorts] [e.g. vCapacity := VarSetStrCapacity(&vText)] [note: VarSetStrCapacity can *get* and set the capacity] C++: capacity [e.g. vCapacity = vText.capacity()] C#: ___ [note: StringBuilder: vCapacity = oSB.Capacity] [requires: using System.Text] Crystal: ___ Excel: ___ Excel VBA: ___ Go: ___ [note: strings.Builder: vCapacity = oSB.Cap()] Java: ___ [note: StringBuilder: vCapacity = oSB.capacity()] JavaScript: ___ Kotlin: ___ [note: StringBuilder: vCapacity = oSB.capacity()] PHP: ___ Python: ___ R: ___ Ruby: ___ Rust: capacity [e.g. vCapacity = vText.capacity()] Scala: ___ [note: StringBuilder: vCapacity = oSB.capacity] SQL (MySQL): ___ SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: ___ UFL: StrSetCapacity [set string capacity (or request a minimum capacity, i.e. set a capacity greater than or equal to the request)][in bytes, unless stated][see also: Array.SetCapacity] Prompt: MyLang, one-liner, input vars oSB/vCapacity (string builder object or string/int). Set the capacity of oSB in bytes based on vCapacity. If not possible, show '___'. AutoHotkey: VarSetStrCapacity [note: in UTF-16 shorts] [e.g. VarSetStrCapacity(&vText, vCapacity)] [WARNING: makes the string blank] C++: reserve [e.g. vText.reserve(vCapacity)] [also: vText.shrink_to_fit()] C#: ___ [note: StringBuilder: oSB.Capacity = vCapacity] [requires: using System.Text] Crystal: new [e.g. new string: vText = String.new(vCapacity){|v| {vCapacity,vCapacity}}] Excel: ___ Excel VBA: ___ Go: ___ [note: strings.Builder: oSB.Grow(vCapacityToAdd)] [WARNING: value is capacity to *add*, not the future total] Java: ___ [note: StringBuilder: oSB.ensureCapacity(vCapacity)] [also: StringBuilder: oSB.trimToSize()] JavaScript: ___ Kotlin: ___ [note: StringBuilder: oSB.ensureCapacity(vCapacity)] [also: StringBuilder: oSB.trimToSize()] PHP: ___ Python: ___ R: ___ Ruby: new [e.g. new string: vText = String.new(capacity:vCapacity)] [e.g. modify string: vText = String.new(vText, capacity:vCapacity)] Rust: reserve [WARNING: value is capacity to *add*, not the future total] [e.g. add: vText.reserve(vCapacityToAdd)] [e.g. set total: vText.reserve(vCapacity-vText.len())] [also: reserve_exact/shrink_to_fit/shrink_to/truncate] Scala: ___ [note: StringBuilder: oSB.ensureCapacity(vCapacity)] SQL (MySQL): ___ SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: ___ UFL: StrReplace [or StrReplaceAll][replace 'before' string with 'after' string (no RegEx), all occurrences, there may be an option to replace the first n occurrences][WARNING: languages may use 0-based/1-based string indexes][see also: RegExReplace] Prompt: MyLang, one-liner, input vars vText/vBefore/vAfter (strings), output var vTextNew (string). Case-sensitive replace every instance of vBefore in vText with vAfter, assign to vTextNew. AutoHotkey: StrReplace [WARNING: case-insensitive by default] [e.g. vTextNew := StrReplace(vText, vBefore, vAfter, 1)] [WARNING: different param order, AHK v1/v2] [WARNING (AHK v1): global variable A_StringCaseSense determines the case-sensitivity for StrReplace(), use RegExReplace() for one-liners that guarantee case-sensitivity] C++: ___ [can use (RegEx): std::string vTextNew = std::regex_replace(vText, std::regex(vBefore), vAfter)] [also (case-sensitive): repeated find() and replace()] [also (case-insensitive): repeated find() and std::search() with custom char comparator function] [requires (regex_replace): #include <regex>] C#: Replace [e.g. vTextNew = vText.Replace(vBefore, vAfter)] Crystal: gsub [e.g. vTextNew = vText.gsub(vBefore, vAfter)] [also: for a single replacement: sub()] Excel: SUBSTITUTE [e.g. =SUBSTITUTE(A1,MyBefore,MyAfter)] [note: case-sensitive] Excel VBA: Replace [e.g. vTextNew = Replace(vText, vBefore, vAfter)] Go: strings.ReplaceAll [e.g. vTextNew := strings.ReplaceAll(vText, vBefore, vAfter)] [also: strings.Replace has a mandatory param 'n', a max number of replacements to do] Java: replace [e.g. vTextNew = vText.replace(vBefore, vAfter)] [WARNING: replaceAll/replaceFirst treat the 'before' string as a RegEx needle] [WARNING: replace/replaceAll both replace all occurrences] JavaScript: replaceAll [e.g. vTextNew = vText.replaceAll(vBefore, vAfter)] [also: replace()] [WARNING: replace(): 'A regexp with the g flag is the only case where replace() replaces more than once.'] Kotlin: replace [e.g. vTextNew = vText.replace(vBefore, vAfter)] PHP: str_replace [e.g. $vTextNew = str_replace($vBefore, $vAfter, $vText)] Python: str.replace [e.g. vTextNew = vText.replace(vBefore, vAfter)] R: ___ [can use: vTextNew = gsub(vBefore, vAfter, vText, fixed=TRUE)] [WARNING: without 'fixed=TRUE', this does a RegEx replacement] [also: for a single replacement: sub()] Ruby: gsub [e.g. vTextNew = vText.gsub(vBefore, vAfter)] [WARNING: replace() modifies the string, it assigns a new value, e.g. vText.replace(vValue)] [also: for a single replacement: sub()] Rust: replace [e.g. vTextNew = vText.replace(vBefore, vAfter)] Scala: replace [e.g. vTextNew = vText.replace(vBefore, vAfter)] [WARNING: replaceAll/replaceFirst treat the 'before' string as a RegEx needle] [WARNING: replace/replaceAll both replace all occurrences] SQL (MySQL): replace [e.g. replace(MyText, MyBefore, MyAfter)] SQL (PostgreSQL): replace [e.g. replace(MyText, MyBefore, MyAfter)] [also: translate(MyText, MyCharsBefore, MyCharsAfter)] SQL (SQLite): replace [e.g. replace(MyText, MyBefore, MyAfter)] Swift: replacingOccurrences [e.g. vText.replacingOccurrences(of:vBefore, with:vAfter)] [requires (replacingOccurrences): import Foundation] UFL: StrReplaceCasIns [replace 'before' string with 'after' string (no RegEx), all occurrences, there may be an option to replace the first n occurrences][note: if using RegEx, '(?i)' typically sets case-insensitivity on][WARNING: languages may use 0-based/1-based string indexes][workaround: RegExReplace][see also: RegExReplace] Prompt: MyLang, one-liner, input vars vText/vBefore/vAfter (strings), output var vTextNew (string). Case-insensitive (accent-sensitive) replace every instance of vBefore in vText with vAfter, assign to vTextNew. AutoHotkey: StrReplace [WARNING: case-insensitive by default] [e.g. case-insensitive: vTextNew := StrReplace(vText, vBefore, vAfter)] [WARNING: AHK v1/v2: AHK v2 adds a CaseSense param, which changes the param order] C++: ___ [can use: repeated find() and std::search() with custom char comparator function] C#: Replace [e.g. vTextNew = vText.Replace(vBefore, vAfter, StringComparison.OrdinalIgnoreCase)] Crystal: ___ Excel: ___ Excel VBA: Replace [e.g. case-insensitive: vTextNew = Replace(vText, vBefore, vAfter, , , 1)] Go: ___ Java: ___ JavaScript: ___ Kotlin: replace [e.g. case-insensitive: vTextNew = vText.replace(vBefore, vAfter, true)] PHP: str_ireplace [e.g. $vTextNew = str_ireplace($vBefore, $vAfter, $vText)] [WARNING: only ASCII chars are replaced case-insensitively, other chars are replaced case-sensitively] Python: ___ R: ___ [can use (RegEx needle): vTextNew = gsub(vBefore, vAfter, vText, ignore.case=TRUE)] [WARNING: you cannot use ignore.case=TRUE and fixed=TRUE at the same time] Ruby: ___ Rust: ___ Scala: ___ SQL (MySQL): ___ [can use (RegEx needle): regexp_replace(MyText, MyNeedle, MyAfter)] [note: regexp_replace() is case-insensitive by default, use 'c' for case-sensitive] SQL (PostgreSQL): ___ [can use (RegEx needle): regexp_replace(MyText, MyNeedle, MyAfter, 1, 0)] SQL (SQLite): ___ Swift: replacingOccurrences [e.g. vTextNew = vText.replacingOccurrences(of:vBefore, with:vAfter, options:.caseInsensitive)] [requires (replacingOccurrences): import Foundation] UFL: StrReplaceMax [or StrReplaceN][replace 'before' string with 'after' string (no RegEx), the first n occurrences][WARNING: languages may use 0-based/1-based string indexes][see also: RegExReplace] Prompt: MyLang, one-liner, input vars vText/vBefore/vAfter/vLimit (string/string/string/int), output var vTextNew (string). Case-sensitive replace the first vLimit instances of vBefore with vAfter, assign to vTextNew. AutoHotkey: StrReplace [WARNING: case-insensitive by default] [e.g. case-sensitive: vTextNew := StrReplace(vText, vBefore, vAfter, 1,, vLimit)] [WARNING: different param order, AHK v1/v2] C++: ___ C#: ___ Crystal: ___ Excel: ___ [can use (replace one instance, the nth instance): =SUBSTITUTE(A1,MyBefore,MyAfter,MyIndex)] [note: case-sensitive] [WARNING: can use multiple nested SUBSTITUTE calls with index set to 1, but avoid if 'after' text contains 'before' text] Excel VBA: Replace [e.g. vTextNew = Replace(vText, vBefore, vAfter, , vLimit)] Go: strings.Replace [e.g. vTextNew := strings.Replace(vText, vBefore, vAfter, vLimit)] Java: ___ [can use (replace first instance, RegEx needle): vTextNew = vText.replaceFirst(vBefore, vAfter)] [WARNING: can use multiple replaceFirst calls, but avoid if 'after' text contains 'before' text] [WARNING: replaceAll/replaceFirst treat the 'before' string as a RegEx needle] [WARNING: replace/replaceAll both replace all occurrences] JavaScript: ___ [can use: vTemp = 0; vTextNew = vText.replace(new RegExp(vBefore, "g"), vMatch=>vTemp++<vLimit?vAfter:vMatch);] Kotlin: ___ [can use (replace first instance, string): vTextNew = vText.replaceFirst(vBefore, vAfter)] [WARNING: can use multiple replaceFirst calls, but avoid if 'after' text contains 'before' text] [note: replace() replaces all occurrences] PHP: ___ Python: str.replace [e.g. vTextNew = vText.replace(vBefore, vAfter, vLimit)] R: ___ Ruby: ___ Rust: replacen [e.g. vTextNew = vText.replacen(vBefore, vAfter, vLimit)] Scala: ___ [can use (replace first instance, RegEx needle): vTextNew = vText.replaceFirst(vBefore, vAfter)] [WARNING: can use multiple replaceFirst calls, but avoid if 'after' text contains 'before' text] [WARNING: replaceAll/replaceFirst treat the 'before' string as a RegEx needle] [WARNING: replace/replaceAll both replace all occurrences] SQL (MySQL): ___ SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: ___ UFL: StrReplaceMult [or StrReplaceAllMult][replace 'before' strings with 'after' strings, no RegEx, all occurrences, multiple passes][WARNING: this is like performing n separate replacements, not one left-to-right parse (single pass) like StrTranslate/RegExReplace, so be careful if the output of one matches the input of another][see also: StrTranslate/RegExReplace] Prompt: MyLang, one-liner, input vars vText/oArrayBefore/oArrayAfter (strings), output var vTextNew (string). Case-sensitive replace every instance of item n in oArrayBefore in vText with item n in oArrayAfter, assign to vTextNew. AutoHotkey: ___ C++: ___ C#: ___ Crystal: ___ Excel: ___ Excel VBA: ___ Go: ___ Java: ___ JavaScript: ___ Kotlin: ___ PHP: $vTextNew = str_replace($oArrayBefore, $oArrayAfter, $vText) Python: ___ R: ___ Ruby: ___ Rust: ___ Scala: ___ SQL (MySQL): ___ SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: ___ UFL: (StrTranslate) [parse each char in a string, one by one, replace any matches][e.g. strip accents: 'áéíóúý' to 'aeiouy'][e.g. base64url to base64: '+/' to '-_'][note: this differs from simply doing multiple replacements, e.g. 'ab' to 'ba', multiple replacements would turn 'a' to 'b' and back to 'a'][see also: RegExReplace/StrLowerAsciiOnly/StrUpperAsciiOnly] Prompt: MyLang, one-liner, input vars vText/vBefore/vAfter (strings), output var vTextNew (string). Do a 'translate', case-sensitive replace every instance of char n in vBefore in vText with char n in vAfter, assign to vTextNew. AutoHotkey: ___ C++: ___ C#: ___ Crystal: tr [e.g. vTextNew = vText.tr(vBefore, vAfter)] Excel: ___ Excel VBA: ___ Go: ___ Java: ___ JavaScript: ___ Kotlin: ___ PHP: strtr [e.g. $vTextNew = strtr($vText, $vBefore, $vAfter)] Python: translate [e.g. vTextNew = vText.translate(str.maketrans(vBefore, vAfter))] R: chartr [e.g. vTextNew = chartr(vBefore, vAfter, vText)] Ruby: tr [e.g. vTextNew = vText.tr(vBefore, vAfter)] Rust: ___ Scala: ___ SQL (MySQL): ___ SQL (PostgreSQL): translate [e.g. translate('abcdefghijklmnopqrstuvwxyz', 'aeiou', 'AEIOU')] SQL (SQLite): ___ Swift: ___ UFL: StrSplit [string to array (split by delimiters)][note: can accept a multi-char string as a separator unless stated][note: see StrSplitChars re. languages where blank string *and* blank delim sometimes returns 1 or more strings][WARNING: some languages have options regarding trimming leading/internal/trailing blank strings, e.g. ',a,b,c,' split by ',' would return 3 not 5 items][see also: StrSplitChars/StrSplitMax/RegExSplit/StrSplitBlankInputDemo/StrSplitBlankSepDemo] Prompt: MyLang, one-liner, input vars vText/vSep (strings), output var oArray (string array). Split vText to array of output strings oArray, based on delimiter vSep. AutoHotkey: StrSplit [e.g. oArray := StrSplit(vText, vSep)] [also (separator array): oArray := StrSplit(vText, oSep)] C++: ___ [can use: repeated find() and substr()] [also (single-char separator only): std::stringstream and getline] [WARNING: getline ignores a blank line after the last separator] [requires (stringstream): #include <sstream>] C#: Split [e.g. oArray = vText.Split(vSep)] [note: C# 9 (.NET 5): accepts a string delimiter, before that, only a char] [also (separator array): oArray = vText.Split(oSep, vOpt)] Crystal: split [e.g. oArray = vText.split(vSep)] Excel: TEXTSPLIT [version: Excel 2024: TEXTSPLIT()] Excel VBA: Split [e.g. oArray = Split(vText, vSep)] Go: strings.Split [e.g. oArray := strings.Split(vText, vSep)] [also (maintain the separators): strings.SplitAfter()] [also (limit to n splits): strings.SplitN()/strings.SplitAfterN()] [also: strings.FieldsFunc()] Java: split [WARNING: splits based on RegEx, not a literal string] [e.g. oArray = vText.split(vSep, -1)] [WARNING: limit param: omitted or 0 to omit trailing blank strings, -1 to maintain them] JavaScript: split [e.g. oArray = vText.split(vSep)] Kotlin: split [e.g. oArray = vText.split(vSep).toTypedArray()] PHP: explode [WARNING: str_split splits into chunks of size n, not by delimiter] [e.g. $oArray = explode($vSep, $vText)] Python: str.split [e.g. oList = vText.split(vSep)] [note: use list to split a string to a list of 1-char strings] [note: str.rsplit returns the last n items if maxsplit is specified] R: strsplit [WARNING: splits based on RegEx, use fixed=TRUE to split based on a literal string] [e.g. oVec = strsplit(vText, vSep, fixed=TRUE)[[1]]] [e.g. oVec = unlist(strsplit(vText, vSep, fixed=TRUE))] [WARNING: omits 1 trailing blank string (if multiple trailing blank strings, only omits the last one)] Ruby: split [e.g. oArray = vText.split(vSep, -1)] [WARNING: limit param: omitted or 0 to omit trailing blank strings, -1 to maintain them] Rust: split [e.g. oVec = vText.split(vSep).collect::<Vec<_>>()] [also: oVec: Vec<&str> = vText.split(vSep).collect()] [also (limit to n splits): splitn()] Scala: split [WARNING: splits based on RegEx, not a literal string] [e.g. oArray = vText.split(vSep, -1)] [WARNING: limit param: omitted or 0 to omit trailing blank strings, -1 to maintain them] SQL (MySQL): ___ [can use (0-based, turn delimiter-separated array into JSON string and lookup): e.g. json_extract('["' || replace('abc,def,ghi,jkl', ',', '","') || '"]', '$[3]')] [requires (||): set sql_mode=PIPES_AS_CONCAT] SQL (PostgreSQL): string_to_array [e.g. string_to_array(MyText, MySep)] [can use (turn delimiter-separated array into JSON string and lookup): e.g. ('["' || replace('abc,def,ghi,jkl', ',', '","') || '"]')::json ->> 3] [also: regexp_split_to_array()] SQL (SQLite): ___ [can use (turn delimiter-separated array into JSON string and lookup): e.g. '["' || replace('abc,def,ghi,jkl', ',', '","') || '"]' ->> 3] Swift: split [e.g. oArray = vText.split(separator:vSep, omittingEmptySubsequences:false).map{String($0)}] [WARNING: omittingEmptySubsequences param: omitted or true to omit all leading/internal/trailing blank strings, false to maintain them] [also: oArray = vText.components(separatedBy:vSep)] [requires (components): import Foundation] UFL: (StrSplitMult) [string to array, split by a delimiter array (split by one or more delimiters)][note: can accept a multi-char string as a separator unless stated][see also: RegExSplit/Array.JoinMult] Prompt: MyLang, one-liner, input vars vText/oSep (string/string array), output var oArray (string array). Split vText to array of output strings oArray, based on delimiter array oSep. Note: equivalent to: in vText, replace oSep needles with a temporary string, split by the temporary string. AutoHotkey: StrSplit [e.g. oArray := StrSplit(vText, oSep)] C++: ___ C#: Split [e.g. oArray = vText.Split(oSep, vOpt)] Crystal: ___ Excel: ___ Excel VBA: ___ Go: ___ Java: ___ JavaScript: ___ Kotlin: ___ PHP: ___ Python: ___ R: ___ Ruby: ___ Rust: ___ Scala: ___ SQL (MySQL): ___ SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: ___ UFL: (StrSplitBlankInputDemo) [whether splitting a blank string, by a delimiter, returns an array of 0 or 1 blank strings][see also: StrSplit] Prompt: MyLang, one-liner. Split a blank string to an array of output strings, based on a delimiter string, a comma. As a comment, print the output. AutoHotkey: StrSplit("", ",").Length [length: 0] C++: ___ C#: "".Split(",").Length [length: 1] Crystal: "".split(",").size [length: 1] Excel: ___ [version: Excel 2024: TEXTSPLIT()] Excel VBA: oArray = Split("", ","): vLen = UBound(oArray) - LBound(oArray) + 1 [length: 0] Go: len(strings.Split("", ",")) [length: 1] Java: "".split(",", -1).length JavaScript: "".split(",").length [length: 1] Kotlin: "".split(",").toTypedArray().count() [length: 1] PHP: count(explode(",", "")) [length: 1] [note: param order: separator, string] Python: len("".split(",")) [length: 1] R: length(strsplit("", ",", fixed=TRUE)[[1]]) [also: unlist(strsplit("", ",", fixed=TRUE))] [length (both): 0] Ruby: "".split(",", -1).length [length: 0] Rust: "".split(",").collect::<Vec<_>>().len() [length: 1] Scala: "".split(",", -1).length [length: 1] SQL (MySQL): ___ SQL (PostgreSQL): string_to_array('', ',') [length: 0] SQL (SQLite): ___ Swift: "".split(separator:",", omittingEmptySubsequences:false).map{String($0)}.count [length: 1] UFL: (StrSplitBlankSepDemo) [or StrSplitBlankDelimDemo][the effect of splitting a non-blank string by a blank delimiter (blank separator), how many strings in the output array][see also: StrSplit] Prompt: MyLang, one-liner. Split string "abc" to an array of output strings, based on a delimiter string, a blank string. As a comment, print the output. AutoHotkey: StrSplit("abc", "") [output: 1 string per char] C++: ___ C#: "abc".Split("") [output: 1 string (entire string)] Crystal: "abc".split("") [output: 1 string per char] Excel: ___ [version: Excel 2024: TEXTSPLIT()] Excel VBA: Split("abc", "") [output: 1 string (entire string)] Go: strings.Split("abc", "") [output: 1 string per char] Java: "abc".split("", -1) [output: 1 string per char, with 1 trailing blank string] JavaScript: "abc".split("") [output: 1 string per char] Kotlin: "abc".split("").toTypedArray() [WARNING: output: 1 string per char, with 2 (leading/trailing) blank strings] PHP: explode("", "abc") [output: throws] Python: "abc".split("") [output: throws] R: strsplit("abc", "", fixed=TRUE)[[1]] [also: unlist(strsplit("abc", "", fixed=TRUE))] [output (both): 1 string per char] Ruby: "abc".split("", -1) [output: 1 string per char, with 1 trailing blank string] Rust: "abc".split("").collect::<Vec<_>>() [WARNING: 1 output string per char, with 2 (leading/trailing) blank strings] Scala: "abc".split("", -1) [output: 1 string per char, with 1 trailing blank string] SQL (MySQL): ___ SQL (PostgreSQL): string_to_array('abc', '') [output: 1 string (entire string)] SQL (SQLite): ___ Swift: "abc".split(separator:"", omittingEmptySubsequences:false).map{String($0)} [output: 1 string per char, with 2 (leading/trailing) blank strings] UFL: (StrSplitBlankInputSepDemo) [or StrSplitBlankInputDelimDemo][the effect of splitting a blank string by a blank delimiter (blank separator), how many strings in the output array][see also: StrSplit] Prompt: MyLang, one-liner. Split a blank string to an array of output strings, based on a delimiter string, a blank string. As a comment, print the output. AutoHotkey: StrSplit("", "") [output: 0 strings] C++: ___ C#: "".Split("") [output: 1 string (blank string)] Crystal: "".split("") [output: 1 string (blank string)] Excel: ___ [version: Excel 2024: TEXTSPLIT()] Excel VBA: Split("", "") [output: 1 string (blank string)] Go: strings.Split("", "") [output: 0 strings] Java: "".split("", -1) [output: 1 string (blank string)] JavaScript: "".split("") [output: 0 strings] Kotlin: "".split("").toTypedArray() [WARNING: output: 0 strings, with 2 (leading/trailing) blank strings] PHP: explode("", "") [output: throws] Python: "".split("") [output: throws] R: strsplit("", "", fixed=TRUE)[[1]] [also: unlist(strsplit("", "", fixed=TRUE))] [output (both): 0 strings] Ruby: "".split("", -1) [output: 0 strings] Rust: "".split("").collect::<Vec<_>>() [output: 0 strings, with 2 (leading/trailing) blank strings] Scala: "".split("", -1) [output: 1 string (blank string)] SQL (MySQL): ___ SQL (PostgreSQL): string_to_array('', '') [output: 0 strings] SQL (SQLite): ___ Swift: "".split(separator:"", omittingEmptySubsequences:false).map{String($0)} [output: 1 string (blank string)] UFL: StrSplitChars [often equivalent to StrChunk(vText, 1)][create an array of strings of length 1][note: splits by codepoints (maintains surrogate pairs) unless stated][WARNING: in some languages, "".split(vSep) returns [""], not []][see also: ChrAt/StrChunk/RegExSplit] Prompt: MyLang, one-liner, input var vText (string), output var oArray (string array). Split string vText to an array of output strings oArray, where each string is 1 Unicode codepoint in length. AutoHotkey: ___ [can use (find a char not in vText first): oArray := StrSplit(RegExReplace(vText, "s)(?<=.)(?=.)", vUnused), vUnused)] [can use: oArray := StrSplit(vText)] [also: StrSplit(vText, "")] [WARNING: StrSplit with omitted/blank separator splits surrogate pairs] [note: split blank string (all approaches): return array length 0] C++: ___ [can use (add a pipe between each codepoint): vTextNew = std::regex_replace(vText, (std::regex)"(?!^)([^\x80-\xBF])", "|$1")] [requires: #include <regex>] [algorithm: if it's not a UTF-8 continuation byte, it's the lead byte (the start of a char)] C#: EnumerateRunes [e.g. string[] oArray = vText.EnumerateRunes().Select(v=>v.ToString()).ToArray()] [also: string[] oArray = Regex.Split(vText, "(?s)(?<=.)(?=.)(?![\uDC00-\uDFFF])")] [also: string[] oArray = Regex.Split(vText, "(?<=.)(?=.)(?![\uDC00-\uDFFF])", RegexOptions.Singleline)] [also: string[] oArray = Regex.Split(vText, @"(?<=[\s\S])(?=[\s\S])(?![\uDC00-\uDFFF])")] [requires (Regex.Split): using System.Text.RegularExpressions] [also: StringInfo.GetTextElementEnumerator] [also: Encoding.UTF32.GetBytes()/BitConverter.ToInt32()/Char.ConvertFromUtf32()] [also (WARNING: splits surrogate pairs): string[] oArray = vText.Select(v=>v.ToString()).ToArray()] [WARNING: split blank string (Regex.Split): return array length 1] Crystal: split [e.g. oArray = vText.split("")] [also: oArray = vText.chars.map{|v| v.to_s}] [also (char array): oArray = vText.chars] [note: creates a copy] [WARNING: split blank string (split()): return array length 1] Excel: ___ Excel VBA: ___ Go: strings.Split [e.g. oArray := strings.Split(vText, "")] [note: split blank string: return array length 0] Java: ___ [can use: String[] oArray = vText.codePoints().mapToObj(Character::toString).toArray(String[]::new)] [also: vText.split("(?s)(?<=.)")] [also (WARNING: splits surrogate pairs): vText.split("")] [WARNING: split blank string (for both approaches using split()): return array length 1] [also: oArray = Pattern.compile("(?s)(?<=.)").split(vText)] [also: oArray = Pattern.compile("(?<=.)", Pattern.DOTALL).split(vText)] JavaScript: ___ [can use: oArray = [...vText]] [note: 'Strings are iterated by Unicode code points.'] [note: split blank string (split()): return array length 0] [also (WARNING: splits any surrogate pairs): vText.split("")] Kotlin: ___ [can use: oArray = vText.codePoints().mapToObj{Character.toString(it)}.toList().toTypedArray()] [also (WARNING: splits surrogate pairs): vText.chunked(1)] [WARNING: split(): returns blank strings at start and end] [WARNING: split blank string (split()): return array length 2] [also: vText.split("").drop(1).dropLast(1)] [note: split blank string (chunked()): return array length 0] PHP: ___ [can use: $oArray = mb_str_split($vText)] [note: split blank string: return array length 0] [WARNING: str_split() (unlike mb_str_split()) splits by bytes] Python: ___ [can use: oList = list(vText)] [note: split blank string: return array length 0] R: strsplit [e.g. oVec = unlist(strsplit(vText, ""))] [note: split blank string: return array length 0] Ruby: chars [e.g. oArray = vText.chars] [note: creates a copy] [also: oArray = vText.split("")] [note: split blank string (split()): return array length 0] Rust: ___ [can use: oVec = vText.chars().map(|v| v.to_string()).collect::<Vec<String>>()] Scala: ___ [can use: oArray = vText.codePoints.mapToObj(Character.toString(_)).toArray] [also: vText.split("(?s)(?<=.)")] [also (WARNING: splits surrogate pairs): vText.split("")] [note: split blank string (for both approaches using split()): return array length 0 (unlike Java)] SQL (MySQL): ___ SQL (PostgreSQL): ___ [can use: string_to_array(MyText, NULL)] SQL (SQLite): ___ [can use: group_concat(substr(MyText, value, 1)) FROM generate_series(1, length(MyText))] Swift: ___ [can use: oArray = vText.map{String($0)}] [note: split blank string: return array length 0] UFL: (StrSplitAZDemo) [or StrSplitAToZDemo][create an array of strings of length 1][note: the approaches below work on ASCII chars, but not necessarily all Unicode codepoints][see also: Array.NewAToZDemo] Prompt: MyLang, one-liner, output var oArray (array). Split string "abcdefghijklmnopqrstuvwxyz" to an array of output strings oArray, where each string is 1 Unicode codepoint in length. AutoHotkey: oArray := StrSplit("abcdefghijklmnopqrstuvwxyz") C++: ___ [can use: std::string oArray[] = {"a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"}] C#: string[] oArray = "abcdefghijklmnopqrstuvwxyz".Select(v=>v.ToString()).ToArray() Crystal: oArray = "abcdefghijklmnopqrstuvwxyz".split("") Excel: ___ Excel VBA: ___ [can use: oArray = Array("a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z")] [also: oArray = Split("a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z", ",")] Go: oArray := strings.Split("abcdefghijklmnopqrstuvwxyz", "") Java: oArray = "abcdefghijklmnopqrstuvwxyz".split("") JavaScript: oArray = [..."abcdefghijklmnopqrstuvwxyz"] [also: oArray = "abcdefghijklmnopqrstuvwxyz".split("")] Kotlin: oArray = "abcdefghijklmnopqrstuvwxyz".chunked(1) PHP: $oArray = mb_str_split("abcdefghijklmnopqrstuvwxyz") Python: oList = list("abcdefghijklmnopqrstuvwxyz") R: oVec = strsplit("abcdefghijklmnopqrstuvwxyz", "") Ruby: oArray = "abcdefghijklmnopqrstuvwxyz".chars [also: oArray = "abcdefghijklmnopqrstuvwxyz".split("")] Rust: oVec = "abcdefghijklmnopqrstuvwxyz".chars().map(|v| v.to_string()).collect::<Vec<String>>() Scala: oArray = "abcdefghijklmnopqrstuvwxyz".split("") [also: oArray = ('a' to 'z').map(_.toString).toArray] SQL (MySQL): ___ SQL (PostgreSQL): string_to_array('abcdefghijklmnopqrstuvwxyz', NULL) SQL (SQLite): ___ Swift: oArray = Array("abcdefghijklmnopqrstuvwxyz").map{String($0)} UFL: StrSplitNthOrDefault [string split by delimiter, return nth item, or if too few items, return default value][see also: StrSplit/InStrNth/Array.GetOrDefault] Prompt: MyLang, one-liner, input vars vText/vSep/vKey/vDefault (string/string/int/string), output var vValue (string). Split string (vText) by delimiter (vSep), return nth item (vKey), else if too few items, return default value (vDefault). AutoHotkey: vValue := (vKey==1) || InStr(vText, vSep,,, vKey-1) ? StrSplit(vText, vSep)[vKey] : vDefault [note: 1-based] C++: ___ C#: vValue = vText.Split(vSep).ElementAtOrDefault(vKey) ?? vDefault [note: if no key is found, ElementAtOrDefault() returns the default value for the type, e.g. null for strings, you can't specify a default value] Crystal: vValue = vText.split(vSep).fetch(vKey, vDefault) Excel: ___ Excel VBA: ___ Go: ___ Java: ___ JavaScript: vValue = vText.split(vSep)[vKey] ?? vDefault Kotlin: vValue = vText.split(vSep).getOrElse(vKey){vDefault} PHP: $vValue = explode($vSep, $vText)[$vKey] ?? $vDefault Python: vValue = (vText.split(vSep)[vKey:vKey+1]or[vDefault])[0] R: vValue = na.omit(c(strsplit(vText, vSep)[[1]][vKey], vDefault))[1] [note: 1-based] Ruby: vValue = vText.split(vSep).fetch(vKey, vDefault) Rust: ___ Scala: vValue = vText.split(vSep).zipWithIndex.find(e=>e._2==vKey).getOrElse((vDefault, 0))._1 SQL (MySQL): ___ [can use (1-based): e.g. substring_index(substring_index('abc,def,ghi' || ',default', ',', MyKey), ',', -1)] [note: a positive index gets the first n substrings, -1 gets the last string] [can use (0-based, turn delimiter-separated array into JSON string and lookup): e.g. json_extract('["' || replace('abc,def,ghi,jkl', ',', '","') || '"]', '$[3]')] [also (RegEx needle): regexp_substr(MyText, MyNeedle, 1, MyOcc, 'c')] [requires (||): set sql_mode=PIPES_AS_CONCAT] SQL (PostgreSQL): ___ [can use (1-based, returns blank if no match): e.g. split_part('abc,def,ghi,jkl', ',', MyKey)] [also (1-based): coalesce((string_to_array(MyText, MySep))[MyKey], MyDefault) [also (turn delimiter-separated array into JSON string and lookup): e.g. ('["' || replace('abc,def,ghi,jkl', ',', '","') || '"]')::json ->> 3] SQL (SQLite): ___ [can use (turn delimiter-separated array into JSON string and lookup): e.g. '["' || replace('abc,def,ghi,jkl', ',', '","') || '"]' ->> 3] Swift: vValue = vText.split(separator:vSep).enumerated().first{$0.offset==vKey}.map{String($1)} ?? vDefault UFL: StrSplitMax [or StrSplitN][string to array (split by delimiters), return a maximum of n array items, where the nth item is the leftover string][typically n indicates max items *including* leftover item][warn below if n indicates max items *excluding* leftover item, i.e. max n+1 items][note: can accept a multi-char string as a separator unless stated][note: see StrSplitChars re. languages where blank string *and* blank delim sometimes returns 1 or more strings] Prompt: MyLang, one-liner, input vars vText/vSep/vMax (string/string/int), output var oArray (array). Split string (vText) to an array by delimiter (vSep), return a maximum of n (vMax) items, where the nth item is the leftover string. AutoHotkey: StrSplit [e.g. oArray := StrSplit(vText, vSep,, vMax)] C++: ___ C#: Split [e.g. oArray = vText.Split(vSep, vMax)] [note: C# 9 (.NET 5): accepts a string delimiter, before that, only a char] Crystal: split [e.g. oArray = vText.split(vSep, vMax)] Excel: ___ Excel VBA: Split [e.g. oArray = Split(vText, vSep, vMax)] Go: strings.SplitN [e.g. oArray := strings.SplitN(vText, vSep, vMax)] [also (maintain the separators): strings.SplitAfterN] [also: strings.FieldsFunc] Java: split [WARNING: splits based on RegEx, not a literal string] [e.g. oArray = vText.split(vSep, vMax)] JavaScript: ___ [WARNING: split with 'limit' param specified: 'Any leftover text is not included in the array at all.' (max n clean items, and never a leftover item)] [can use: oArray = [vText.split(vSep, vMax-1), [vText.split(vSep).slice(vMax-1)].map(v=>v.length?v.join(vSep):[])].flat(2)] [note: split(sep, n-1) returns a max of n-1 items, split(sep).slice(n-1) splits then removes the first n-1 items] Kotlin: split [e.g. oArray = vText.split(vSep, limit=vMax).toTypedArray()] PHP: explode [WARNING: str_split splits into chunks of size n, not by delimiter] [e.g. $oArray = explode($vSep, $vText, $vMax)] Python: str.split [e.g. oList = vText.split(vSep, vMax-1)] [WARNING: unlike in most languages, maxsplit=n can return an array of n+1 items (max n clean items, and a possible leftover item)] [note: str.rsplit returns the last n items if maxsplit is specified] R: ___ Ruby: split [e.g. oArray = vText.split(vSep, vMax)] Rust: split [e.g. oVec: Vec<&str> = vText.splitn(vMax, vSep).collect()] Scala: split [WARNING: splits based on RegEx, not a literal string] [e.g. oArray = vText.split(vSep, vMax)] SQL (MySQL): ___ SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: split [e.g. oArray = vText.split(separator:vSep, maxSplits:vMax-1, omittingEmptySubsequences:false).map{String($0)}] [WARNING: unlike in most languages, maxSplits=n can return an array of n+1 items (max n clean items, and a possible leftover item)] UFL: StrChunk [or StrSplitLen][string to array (split into chunks of n chars)][workaround: RegExReplace and StrSplit][see also: StrHatch/Array.Chunk/RegExReplace/RegExSplit] Prompt: MyLang, one-liner, input vars vText/vCount (string/int), output var oArray (array). Split string (vText) to an array (oArray), split into chunks of n (vCount) chars (1 char per Unicode codepoint). AutoHotkey: ___ [can use (keeps surrogate pairs): oArray := StrSplit(RegExReplace(vText, ".{" vCount "}(?=.)", "$0" vUnused))] [note: where vText does not contain vUnused] [note (RegEx): vUnused: '$' needs escaping as '$$'] C++: ___ C#: ___ [can use (keeps surrogate pairs): oArray = Regex.Split(vText, "(?<=\\G(?:[^\uDC00-\uDFFF][\uDC00-\uDFFF]?){4})(?![\uDC00-\uDFFF]|$)")] [also (can split surrogate pairs): oArray = Regex.Split(vText, "(?<=\\G.{4})(?!$)")] Crystal: ___ [can use (keeps surrogate pairs): oRegEx = Regex.new(".{4}\\K"); oArray = vText.split(oRegEx, remove_empty:true)] Excel: ___ Excel VBA: ___ Go: ___ Java: ___ [can use (can split surrogate pairs): oArray = vText.split("(?<=\\G.{4})")] JavaScript: ___ [can use (keeps surrogate pairs): oRegEx = new RegExp("(.[\uDC00-\uDFFF]?){1,4}", "g"); oArray = vText.match(oRegEx)||[];] [can use (can split surrogate pairs): oRegEx = new RegExp(".{1,4}", "g"); oArray = vText.match(oRegEx)||[];] Kotlin: chunked [e.g. (can split surrogate pairs): oArray = vText.chunked(4).toTypedArray()] [also (fails on surrogate pairs): var oRegEx = Regex("(?<=\\G.{4})(?!$)"); var oArray = vText.split(oRegEx).toTypedArray()] PHP: mb_str_split [e.g. (keeps surrogate pairs): $oArray = mb_str_split($vText, 4)] [also (keeps surrogate pairs): $oArray = preg_split("/.{4}\\K(?!$)/u", $vText)] [WARNING: str_split() splits into n-byte chunks (UTF-8 bytes), whereas mb_str_split() splits into n-codepoint chunks] [WARNING: unlike other 'split' methods, str_split()/mb_str_split() split into chunks of size n, not by delimiter] Python: ___ [can use (keeps surrogate pairs): oList = re.findall(".{1,4}", vText)] [requires: import re] R: ___ [can use (keeps surrogate pairs): oVec = seq(1, nchar(vText), vCount); oVec = substring(vText, oVec, oVec+(vCount-1))] [also (keeps surrogate pairs): oVec = strsplit(vText, ".{4}\\K", perl=TRUE)[[1]]] [also (keeps surrogate pairs): oVec = strsplit(vText, "(?<=\\G.{4})", perl=TRUE)[[1]]] [note: '\K', '\G' and look-behinds require 'perl=TRUE'] Ruby: ___ [can use (keeps surrogate pairs): oRegEx = Regexp.new(".{4}\\K"); oArray = vText.split(oRegEx)] [can use (keeps surrogate pairs, algorithm uses look-ahead but not \G or \K): oArray = vText.reverse.split(/(?=(?:.{4})+$)/).reverse.map(&:reverse)] Rust: ___ [can use (keeps surrogate pairs): oVec = vText.chars().collect::<Vec<char>>().chunks(vCount).map(|v| v.iter().collect::<String>()).collect::<Vec<String>>()] Scala: ___ [can use (can split surrogate pairs): oArray = vText.grouped(vCount).toArray] [can use (fails on surrogate pairs): oArray = vText.split("(?<=\\G.{4})")] SQL (MySQL): ___ SQL (PostgreSQL): ___ [can use (splits right-to-left, keeps surrogate pairs): regexp_split_to_array(MyText, '(?=(.{4})*$)')] SQL (SQLite): ___ Swift: ___ UFL: (StrHatch) [or StrChunkJoin][add a separator every n chars][WARNING: no obvious function name for this, some creativity was required][see also: RegExReplace/StrChunk/StrJoin/FormatNum] Prompt: MyLang, one-liner, input vars vText/vSep/vCount (string/string/int), output var vTextNew (string). Add a separator string (vSep) every n (vCount) chars (1 char per Unicode codepoint). AutoHotkey: ___ [can use (keeps surrogate pairs): vTextNew := RegExReplace(vText, ".{" vCount "}(?=.)", "$0" vSep)] [note (RegEx): vSep: '$' needs escaping as '$$'] C++: ___ C#: ___ Crystal: ___ Excel: ___ Excel VBA: ___ Go: ___ Java: ___ JavaScript: ___ Kotlin: ___ PHP: ___ [can use (keeps surrogate pairs): $vTextNew = implode($vSep, mb_str_split($vText, $vCount))] [can use (can split non-ASCII chars, including surrogate pairs): $vTextNew = chunk_split($vText, $vCount, $vSep)] [WARNING (chunk_split): always appends a trailing separator] [WARNING (chunk_split): unlike other 'chunk' methods, doesn't split to an array, adds a separator every n chars] Python: ___ R: ___ Ruby: ___ Rust: ___ [can use (keeps surrogate pairs): vTextNew = vText.chars().collect::<Vec<char>>().chunks(vCount).map(|v| v.iter().collect::<String>()).collect::<Vec<String>>().join(vSep)] Scala: ___ [can use (can split surrogate pairs): vTextNew = vText.grouped(vCount).mkString(vSep)] SQL (MySQL): ___ SQL (PostgreSQL): ___ SQL (SQLite): ___ [can use (keeps surrogate pairs): group_concat(substr(MyText, (value-1)*MyCount+1, MyCount), MySep) FROM generate_series(1,ceil(1.0*length(MyText)/MyCount))] Swift: ___ UFL: StrJoin [specify a separator string, and one or more strings (or an array) to join][see also: Array.Join/Array.NewStrDemo] Prompt: MyLang, one-liner, input vars vSep/vText1/vText2/vText3 (strings). Join strings (vText1/vText2/vText3) using a separator string (vSep). AutoHotkey: ___ C++: ___ [can use: repeated +=] [also: note: strcat/wcscat] C#: Join [e.g. vTextNew = String.Join(vSep, vText1, vText2, vText3)] [also: String.Join(vSep, oArray)] Crystal: ___ [can use: vTextNew = [vText1, vText2, vText3].join(vSep)] [also: oArray.join(vSep)] Excel: TEXTJOIN [e.g. =TEXTJOIN(MySep,, MyText1, MyText2, MyText3)] [version: Excel 2016: TEXTJOIN()] Excel VBA: WorksheetFunction.TextJoin [also: vTextNew = Join(Array(vText1, vText2, vText3), vSep)] [also: Join(oArray, vSep)] [version: Excel 2016: TEXTJOIN()] Go: ___ [can use: vTextNew := strings.Join([]string{vText1, vText2, vText3}, vSep)] [also: strings.Join(oArray, vSep)] Java: join [e.g. vTextNew = String.join(vSep, vText1, vText2, vText3)] [also: String.join(vSep, oArray)] JavaScript: ___ [can use: vTextNew = [vText1, vText2, vText3].join(vSep)] [also: oArray.join(vSep)] Kotlin: ___ [can use: vTextNew = listOf(vText1, vText2, vText3).joinToString(vSep)] [also: oArray.joinToString(vSep)] PHP: ___ [can use: $vTextNew = implode($vSep, [$vText1, $vText2, $vText3])] [also: implode($vSep, $oArray)] [alias (implode): join] Python: ___ [can use (str.join): vTextNew = vSep.join([vText1, vText2, vText3])] [also: e.g. vSep.join(oList)] [WARNING: can't do: oList.join(vSep)] R: paste [e.g. vTextNew = paste(vText1, vText2, vText3, sep=vSep)] [also: paste(oVec, collapse=vSep)] [also: paste(oVec1, oVec2, sep=vSep1, collapse=vSep2)] [e.g. paste(c("A","B","C"), c("a","b","c"), sep=":", collapse=",") returns 'A:a,B:b,C:c'] [note: default value: sep=" "] Ruby: ___ [can use: vTextNew = [vText1, vText2, vText3].join(vSep)] [also: oArray.join(vSep)] Rust: ___ [can use: vTextNew = [vText1, vText2, vText3].join(vSep)] [also: oArray.join(vSep)] Scala: String.join [e.g. vTextNew = String.join(vSep, vText1, vText2, vText3)] [also: oArray.mkString(vSep)] SQL (MySQL): concat_ws [e.g. concat_ws(',', 'abc', 'def', 'ghi', 'jkl')] [note: concat_ws: 'concatenate with separator'] [note: nulls are omitted] SQL (PostgreSQL): concat_ws [e.g. concat_ws(',', 'abc', 'def', 'ghi', 'jkl')] [note: concat_ws: 'concatenate with separator'] [also: array_to_string(ARRAY[MyText1, MyText2, MyText3], MySep)] [MAJOR WARNING: PostgreSQL has a 100-param limit (max_function_args), use array_to_string() or repeated || as a workaround] [note: nulls are omitted] SQL (SQLite): concat_ws [e.g. concat_ws(',', 'abc', 'def', 'ghi', 'jkl')] [note: concat_ws: 'concatenate with separator'] [MAJOR WARNING: SQLite had an 'about 100'-param limit (e.g. 127) (SQLITE_MAX_FUNCTION_ARG) until v3.48.0, use repeated || as a workaround] [WARNING: concat_ws() in SQLite v3.44-v3.50.1 had a bug where blank strings were omitted, workaround: group_concat(value, ',') FROM json_each(json_array('|', 'a', '', 'b', NULL, 'c'))] [note: nulls are omitted] Swift: ___ [can use: vTextNew = [vText1, vText2, vText3].joined(separator:vSep)] [also: oArray.joined(separator:vSep)] UFL: StrContains [does string contain substring, return a bool][see also: StrEquals/StrStarts/StrEnds/RegExContains] Prompt: MyLang, one-liner, input vars vText/vNeedle (strings), output var vIsMatch (bool). Does a string (vText) contain a substring (vNeedle), return a bool. AutoHotkey: InStr [e.g. case-sensitive: vIsMatch := !!InStr(vText, vNeedle, 1)] [note (InStr): 1-based, returns 0 if no match] [WARNING: case-insensitive by default] C++: contains [e.g. vIsMatch = vText.contains(vNeedle)] [also: vIsMatch = (vText.find(vNeedle) != std::string::npos)] C#: Contains [e.g. vIsMatch = vText.Contains(vNeedle)] Crystal: includes [e.g. vIsMatch = vText.includes?(vNeedle)] Excel: ___ [can use: =ISNUMBER(FIND(MyNeedle,A1))] [note: FIND() returns #VALUE! error if no match] Excel VBA: InStr [e.g. case-sensitive: vIsMatch = (InStr(1, vText, vNeedle) <> 0)] [note: 1-based, returns 0 if no match] Go: strings.Contains [e.g. vIsMatch := strings.Contains(vText, vNeedle)] Java: contains [e.g. vIsMatch = vText.contains(vNeedle)] JavaScript: includes [e.g. vIsMatch = vText.includes(vNeedle)] [also: vIsMatch = (vText.indexOf(vNeedle) != -1)] Kotlin: contains [e.g. vIsMatch = vText.contains(vNeedle)] PHP: str_contains [e.g. vIsMatch = str_contains($vText, $vNeedle)] Python: in [e.g. vIsMatch = (vNeedle in vText)] [can use: vIsMatch = (vText.find(vNeedle) != -1)] [inverse: vNeedle not in vText] [note: word order: 'not in' versus 'is not'] R: grepl [e.g. vIsMatch = grepl(vNeedle, vText, fixed=TRUE)] [WARNING: without 'fixed=TRUE', this does a RegEx search] Ruby: include [e.g. vIsMatch = vText.include?(vNeedle)] Rust: contains [e.g. vIsMatch = vText.contains(vNeedle)] Scala: contains [e.g. vIsMatch = vText.contains(vNeedle)] SQL (MySQL): instr [e.g. (bool as int): NOT NOT instr(MyText, MyNeedle)] [note (instr): 1-based, returns 0 if no match] [also: LIKE] SQL (PostgreSQL): ___ [can use (bool as int): strpos(MyText, MyNeedle)::bool::int] [also (bool): (strpos(MyText, MyNeedle) != 0)] [note (strpos): 1-based, returns 0 if no match] [also (bool as int): sign(strpos(MyText, MyNeedle))] [also: LIKE] SQL (SQLite): instr [e.g. (bool as int): NOT NOT instr(MyText, MyNeedle)] [note (instr): 1-based, returns 0 if no match] [also: glob('*' || MyNeedle || '*', MyText)] [also (case-insensitive): like('%' || MyNeedle || '%', MyText)] [WARNING: LIKE is case-insensitive for ASCII letters (A-Za-z)] [note (LIKE): % matches 0 or more chars, _ matches 1 char] [WARNING: glob/like: the haystack may contain wildcards] Swift: contains [e.g. vIsMatch = vText.contains(vNeedle)] UFL: StrContainsAll [for a needle array, does the haystack contain all the needles][see also: Array.All/Array.AllEqual] Prompt: MyLang, one-liner, input vars vText/oNeedles (string/array), output var vBool (bool). Does a string (vText) contain all the substrings (oNeedles), return a bool. In blocks, use the default placeholder, e.g. 'it'/'$0', else 'v'. AutoHotkey: ___ C++: vBool = std::all_of(std::begin(oNeedles), std::end(oNeedles), [vText](std::string v){return (vText.find(v) != std::string::npos);}) C#: vBool = oNeedles.All(v=>vText.Contains(v)) Crystal: vBool = oNeedles.all?{|v| vText.includes?(v)} Excel: ___ Excel VBA: ___ Go: ___ Java: vBool = Arrays.stream(oNeedles).allMatch(v->vText.contains(v)) JavaScript: vBool = oNeedles.every(v => vText.includes(v)) Kotlin: vBool = oNeedles.all{vText.contains(it)} PHP: $vBool = array_all($oNeedles, fn($v)=>str_contains($vText, $v)) Python: vBool = all(v in vText for v in oNeedles) R: vBool = all(sapply(oNeedles, grepl, x=vText, fixed=TRUE)) Ruby: vBool = oNeedles.all?{|v| vText.include?(v)} Rust: vBool = oNeedles.iter().all(|&v| vText.contains(v)) Scala: vBool = oNeedles.forall(vText.contains(_)) SQL (MySQL): ___ SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: vBool = oNeedles.allSatisfy{vText.contains($0)} UFL: StrContainsAny [for a needle array, does the haystack contain at least one needle][see also: Array.Any/Array.HasVal] Prompt: MyLang, one-liner, input vars vText/oNeedles (string/array), output var vBool (bool). Does a string (vText) contain at least one of the substrings (oNeedles), return a bool. In blocks, use the default placeholder, e.g. 'it'/'$0', else 'v'. AutoHotkey: ___ C++: vBool = std::any_of(std::begin(oNeedles), std::end(oNeedles), [vText](std::string v){return (vText.find(v) != std::string::npos);}) C#: vBool = oNeedles.Any(v=>vText.Contains(v)) Crystal: vBool = oNeedles.any?{|v| vText.includes?(v)} Excel: ___ Excel VBA: ___ Go: ___ Java: vBool = Arrays.stream(oNeedles).anyMatch(v->vText.contains(v)) JavaScript: vBool = oNeedles.some(v => vText.includes(v)) Kotlin: vBool = oNeedles.any{vText.contains(it)} PHP: $vBool = array_any($oNeedles, fn($v)=>str_contains($vText, $v)) Python: vBool = any(v in vText for v in oNeedles) R: vBool = any(sapply(oNeedles, grepl, x=vText, fixed=TRUE)) Ruby: vBool = oNeedles.any?{|v| vText.include?(v)} Rust: vBool = oNeedles.iter().any(|&v| vText.contains(v)) Scala: vBool = oNeedles.exists(vText.contains(_)) SQL (MySQL): ___ SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: vBool = oNeedles.contains(where:{vText.contains($0)}) UFL: StrContainsCount [for a needle array, how many does the haystack contain][see also: Array.Count/Array.CountMatchNeedleDemo] Prompt: MyLang, one-liner, input vars vText/oNeedles (string/array), output var vCount (int). For a string (vText), how many substrings (oNeedles) does it contain. In blocks, use the default placeholder, e.g. 'it'/'$0', else 'v'. AutoHotkey: ___ C++: vCount = std::count_if(std::begin(oNeedles), std::end(oNeedles), [vText](std::string v){return (vText.find(v) != std::string::npos);}) C#: vCount = oNeedles.Count(v=>vText.Contains(v)) Crystal: vCount = oNeedles.count{|v| vText.includes?(v)} Excel: ___ Excel VBA: ___ [related: check one needle against multiple haystacks: Filter(oHaystacks, vNeedle)] Go: ___ Java: ___ [can use: vCount = Arrays.stream(oNeedles).filter(v->vText.contains(v)).count()] JavaScript: ___ [can use: vCount = oNeedles.filter(v => vText.includes(v)).length] Kotlin: vCount = oNeedles.count{vText.contains(it)} PHP: ___ [can use: $vCount = count(array_filter($oNeedles, fn($v)=>str_contains($vText, $v)))] Python: ___ [can use: vCount = len(list(filter(lambda v:v in vText, oNeedles)))] R: vCount = sum(sapply(oNeedles, grepl, x=vText, fixed=TRUE)) Ruby: vCount = oNeedles.count{|v| vText.include?(v)} Rust: ___ [can use: vCount = oNeedles.iter().filter(|v| vText.contains(**v)).count()] Scala: vCount = oNeedles.count(vText.contains(_)) SQL (MySQL): ___ SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: vCount = oNeedles.count(where:{vText.contains($0)}) UFL: StrContainsIndex [for a needle array, return the index of the first needle that the haystack contains][see also: Array.FindIndex/Array.FilterIndex/Array.IndexOf] Prompt: MyLang, one-liner, input vars vText/oNeedles (string/array), output var vKey (int). For a string (vText), return the index of the first needle (in oNeedles) that it contains. In blocks, use the default placeholder, e.g. 'it'/'$0', else 'v'. AutoHotkey: ___ C++: auto oIter = std::find_if(std::begin(oNeedles), std::end(oNeedles), [vText](std::string v){return (vText.find(v) != std::string::npos);}); auto vKey = (oIter != std::end(oNeedles)) ? oIter-std::begin(oNeedles) : -1; C#: vKey = oNeedles.ToList().FindIndex(v=>vText.Contains(v)) Crystal: vKey = oNeedles.index{|v| vText.includes?(v)} || -1 Excel: ___ Excel VBA: ___ Go: ___ [can use: oFunc := func(v string) bool { return strings.Contains(vText, v) }; vKey := slices.IndexFunc(oNeedles, oFunc)] Java: ___ [can use: vKey = IntStream.range(0, oNeedles.length).filter(i->vText.contains(oNeedles[i])).findFirst().orElse(-1)] JavaScript: vKey = oNeedles.findIndex(v => vText.includes(v)) Kotlin: vKey = oNeedles.indexOfFirst{vText.contains(it)} PHP: $vKey = array_find_key($oNeedles, fn($v,$k)=>str_contains($vText, $v)) Python: ___ [can use: vKey = next((k for k,v in enumerate(oNeedles) if v in vText), -1)] R: vKey = Position(\(v) grepl(v, x=vText, fixed=TRUE), oNeedles) [note: 1-based] Ruby: vKey = oNeedles.index{|v| vText.include?(v)} || -1 Rust: vKey = oNeedles.iter().position(|&v| vText.contains(v)).map_or(-1, |v| v as i32) Scala: vKey = oNeedles.indexWhere(vText.contains(_)) SQL (MySQL): ___ SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: vKey = oNeedles.firstIndex(where:{vText.contains($0)}) ?? -1 UFL: StrContainsFindAll [or StrContainsFilter][for a needle array, return the needles that the haystack contains][see also: Array.Filter/Array.Find] Prompt: MyLang, one-liner, input vars vText/oNeedles (string/array), output var oArray (array). For a string (vText), return the needles (in oNeedles) that it contains. In blocks, use the default placeholder, e.g. 'it'/'$0', else 'v'. AutoHotkey: ___ C++: std::vector<std::string> oVec; std::copy_if(std::begin(oNeedles), std::end(oNeedles), std::back_inserter(oVec), [vText](std::string v){return (vText.find(v) != std::string::npos);}); C#: oArray = oNeedles.Where(v=>vText.Contains(v)).ToArray() Crystal: oArray = oNeedles.select{|v| vText.includes?(v)} Excel: ___ Excel VBA: ___ [related: check one needle against multiple haystacks: Filter(oHaystacks, vNeedle)] Go: ___ Java: String[] oArray = Arrays.stream(oNeedles).filter(v->vText.contains(v)).toArray(String[]::new) JavaScript: oArray = oNeedles.filter(v => vText.includes(v)) Kotlin: oArray = oNeedles.filter{vText.contains(it)}.toTypedArray() PHP: $oArray = array_values(array_filter($oNeedles, fn($v)=>str_contains($vText, $v))) Python: oList = list(filter(lambda v:v in vText, oNeedles)) R: oVec = oNeedles[sapply(oNeedles, grepl, x=vText, fixed=TRUE)] Ruby: oArray = oNeedles.select{|v| vText.include?(v)} Rust: oVec = oNeedles.iter().filter(|v| vText.contains(**v)).collect::<Vec<_>>() Scala: oArray = oNeedles.filter(vText.contains(_)) SQL (MySQL): ___ SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: oArray = oNeedles.filter{vText.contains($0)} UFL: InStr [or StrIndex][does string contain substring, return index of first match][search left-to-right][WARNING: languages may use 0-based/1-based string indexes][see also: InStrRev/StrContains/RegExIndex] Prompt: MyLang, one-liner, input vars vText/vNeedle (strings), output var vPos (int). Does a string (vText) contain a substring (vNeedle), return the index of the first match. AutoHotkey: InStr [e.g. case-sensitive: vPos := InStr(vText, vNeedle, 1)] [note: 1-based, returns 0 if no match] [WARNING: case-insensitive by default] C++: find [e.g. vPos = vText.find(vNeedle)] [note: returns std::string::npos if no match] [also (case-insensitive, forwards or backwards): std::search with custom char comparator function] [also: strstr/wcsstr] C#: IndexOf [e.g. vPos = vText.IndexOf(vNeedle)] [note: returns -1 if no match] Crystal: index [e.g. vPos = vText.index(vNeedle)] [note: returns nil if no match] Excel: FIND [e.g. =FIND(MyNeedle,A1)] [note: 1-based, returns #VALUE! error if no match] [also (returns 0 if no match): =IFERROR(FIND(MyNeedle,A1),0)] [WARNING: FIND() is case-sensitive, SEARCH() is case-insensitive] Excel VBA: InStr [e.g. case-sensitive: vPos = InStr(1, vText, vNeedle)] [note: 1-based, returns 0 if no match] Go: strings.Index [e.g. vPos := strings.Index(vText, vNeedle)] [note: returns -1 if no match] Java: indexOf [e.g. vPos = vText.indexOf(vNeedle)] [note: returns -1 if no match] JavaScript: indexOf [e.g. vPos = vText.indexOf(vNeedle)] [note: returns -1 if no match] Kotlin: indexOf [e.g. vPos = vText.indexOf(vNeedle)] [note: returns -1 if no match] PHP: mb_strpos [e.g. $vPos = mb_strpos($vText, $vNeedle)] [also (case-insensitive): mb_stripos] [WARNING: returns false if no match] [also (bytes): strpos, stripos] [note: strpos v. strrpos] Python: str.find [e.g. vPos = vText.find(vNeedle)] [note: returns -1 if no match] [note: str.index throws if no match] R: regexpr [e.g. vPos = regexpr(vNeedle, vText, fixed=TRUE)[1]] [note: 1-based, returns -1 if no match] [WARNING: without 'fixed=TRUE', this does a RegEx search] Ruby: index [e.g. vPos = vText.index(vNeedle)] [note: returns nil if no match] Rust: find [e.g. oPosOpt = vText.find(vNeedle)] [e.g. vIsMatch = oPosOpt.is_some()] [e.g. vPos = oPosOpt.unwrap()] [note: offsets are in bytes] Scala: indexOf [e.g. vPos = vText.indexOf(vNeedle)] [note: returns -1 if no match] SQL (MySQL): instr [e.g. instr(BINARY MyText, MyNeedle)] [note: 1-based, returns 0 if no match] [also: locate(MyNeedle, BINARY MyText, MyPos)] [also: match] [also: position(MyNeedle IN BINARY MyText)] SQL (PostgreSQL): strpos [e.g. strpos(MyText, MyNeedle)] [note: 1-based, returns 0 if no match] [also: position(MyNeedle IN MyText)] SQL (SQLite): instr [e.g. instr(MyText, MyNeedle)] [note: 1-based, returns 0 if no match] Swift: range [e.g. var oRange = vText.range(of:vNeedle); var vPos = (oRange != nil) ? vText.distance(from:vText.startIndex, to:oRange!.lowerBound) : -1] [requires: import Foundation] UFL: (InStrBlankNeedleDemo) [or StrIndexBlankNeedleDemo][result of using technique described in InStr section above, with a blank needle][test with a blank and non-blank haystack] Prompt: MyLang. State the result of using the string indexOf() method, or equivalent, with haystack "abc" and a blank needle. AutoHotkey: ___ [note: blank needle, throws (AHK v1: returns 1 (1-based))] C++: ___ [note: blank needle, returns 0] C#: ___ [note: blank needle, returns 0] Crystal: ___ [note: blank needle, returns 0] Excel: ___ [note: blank needle, returns 1 (1-based)] Excel VBA: ___ [note: blank needle, 1-based: returns 1 for non-blank haystack, returns 0 (non-match) for blank haystack] Go: ___ [note: blank needle, returns 0] Java: ___ [note: blank needle, returns 0] JavaScript: ___ [note: blank needle, returns 0] Kotlin: ___ [note: blank needle, returns 0] PHP: ___ [note: blank needle, returns 0] Python: ___ [note: blank needle, returns 0] R: ___ [note: blank needle, returns 1 (1-based)] Ruby: ___ [note: blank needle, returns 0] Rust: ___ [note: blank needle, returns 0] Scala: ___ [note: blank needle, returns 0] SQL (MySQL): ___ [note: blank needle, returns 1 (1-based)] SQL (PostgreSQL): ___ [note: blank needle, returns 1 (1-based)] SQL (SQLite): ___ [note: blank needle, returns 1 (1-based)] Swift: ___ [note: blank needle, returns -1 (non-match)] UFL: InStrCasIns [or StrIndexCasIns][search left-to-right][WARNING: languages may use 0-based/1-based string indexes][workaround: RegExIndex][see also: InStrRev/StrContains/RegExIndex] Prompt: MyLang, one-liner, input vars vText/vNeedle (strings), output var vPos (int). Does a string (vText) contain a substring (vNeedle), return the index of the first match. Use a case-insensitive (accent-sensitive) search. AutoHotkey: InStr [e.g. case-insensitive: vPos := InStr(vText, vNeedle)] [note: 1-based, returns 0 if no match] [WARNING: case-insensitive by default] C++: ___ [also (case-insensitive, forwards or backwards): std::search with custom char comparator function] C#: IndexOf [e.g. vPos = vText.IndexOf(vNeedle, StringComparison.OrdinalIgnoreCase)] [note: returns -1 if no match] Crystal: ___ Excel: SEARCH [e.g. =SEARCH(MyNeedle,A1)] [note: 1-based, returns #VALUE! error if no match] [also (returns 0 if no match): =IFERROR(SEARCH(MyNeedle,A1),0)] [WARNING: FIND() is case-sensitive, SEARCH() is case-insensitive] Excel VBA: InStr [e.g. vPos = InStr(1, vText, vNeedle, 1)] [note: 1-based, returns 0 if no match] Go: ___ Java: ___ JavaScript: ___ [can use: vPos = vText.toLowerCase().indexOf(vNeedle.toLowerCase())] Kotlin: indexOf [e.g. case-insensitive: vPos = vText.indexOf(vNeedle, 0, true)] [note: returns -1 if no match] PHP: mb_stripos [e.g. $vPos = mb_stripos($vText, $vNeedle)] [WARNING: returns false if no match] [also (case-insensitive, bytes): stripos] Python: ___ R: ___ [can use (RegEx needle): vPos = regexpr(vNeedle, vText, ignore.case=TRUE)[1]] [note: 1-based, returns -1 if no match] [WARNING: you cannot use ignore.case=TRUE and fixed=TRUE at the same time] Ruby: ___ Rust: ___ Scala: ___ SQL (MySQL): instr [e.g. instr(lower(MyText), lower(MyNeedle))] [note: 1-based, returns 0 if no match] SQL (PostgreSQL): strpos [e.g. strpos(lower(MyText), lower(MyNeedle))] [note: 1-based, returns 0 if no match] SQL (SQLite): instr [e.g. instr(lower(MyText), lower(MyNeedle))] [note: 1-based, returns 0 if no match] Swift: range [e.g. var oRange = vText.range(of:vNeedle, options:.caseInsensitive); var vPos = (oRange != nil) ? vText.distance(from:vText.startIndex, to:oRange!.lowerBound) : -1] [requires: import Foundation] UFL: InStrRev [or StrIndexRev][search right-to-left][get position of last occurrence of substring][WARNING: languages may use 0-based/1-based string indexes][workaround: RegExAll get last][see also: InStr/StrContains/RegExIndex/RegExAll] Prompt: MyLang, one-liner, input vars vText/vNeedle (strings), output var vPos (int). Does a string (vText) contain a substring (vNeedle), return the index of the last match. AutoHotkey: InStr [e.g. case-sensitive (AHK v2): vPos := InStr(vText, vNeedle, 1,, -1)] [note: 1-based, returns 0 if no match] [WARNING: case-insensitive by default] C++: rfind [e.g. vPos = vText.rfind(vNeedle)] [note: returns std::string::npos if no match] [also (case-insensitive, forwards or backwards): std::search with custom char comparator function] C#: LastIndexOf [e.g. vPos = vText.LastIndexOf(vNeedle)] [note: returns -1 if no match] Crystal: rindex [e.g. vPos = vText.rindex(vNeedle)] [note: returns nil if no match] Excel: ___ [can use (find last): get needle string count (LEN/SUBSTITUTE), replace last needle occurrence with temporary char e.g. CHAR(1) (SUBSTITUTE), find char (FIND) (note: '0+' '+0' put around string count for clarity): =FIND(CHAR(1),SUBSTITUTE(A1,B1,CHAR(1),0+(LEN(A1)-LEN(SUBSTITUTE(A1,B1,"")))/LEN(B1)+0))] [note: 1-based, returns #VALUE! error if no match] Excel VBA: InStrRev [e.g. case-sensitive: vPos = InStrRev(vText, vNeedle)] [note: 1-based, returns 0 if no match] Go: strings.LastIndex [e.g. vPos := strings.LastIndex(vText, vNeedle)] [note: returns -1 if no match] Java: lastIndexOf [e.g. vPos = vText.lastIndexOf(vNeedle)] [note: returns -1 if no match] JavaScript: lastIndexOf [e.g. vPos = vText.lastIndexOf(vNeedle)] [note: returns -1 if no match] Kotlin: lastIndexOf [e.g. vPos = vText.lastIndexOf(vNeedle)] [note: returns -1 if no match] [note: don't confuse with indexOfLast] PHP: mb_strrpos [e.g. $vPos = mb_strrpos($vText, $vNeedle)] [also (case-insensitive): mb_strripos] [WARNING: returns false if no match] [also (bytes): strrpos, strripos] [note: strpos v. strrpos] Python: str.rfind [e.g. vPos = vText.rfind(vNeedle)] [note: returns -1 if no match] [note: str.rindex throws if no match] R: ___ Ruby: rindex [e.g. vPos = vText.rindex(vNeedle)] [note: returns nil if no match] Rust: rfind [e.g. oPosOpt = vText.rfind(vNeedle)] [e.g. vIsMatch = oPosOpt.is_some()] [e.g. vPos = oPosOpt.unwrap()] [note: offsets are in bytes] Scala: lastIndexOf [note: returns -1 if no match] SQL (MySQL): ___ SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: ___ UFL: InStrNth [or StrIndexNth][get position of nth occurrence of substring][also: check if a string appears at least n times, 'string count at least'][workaround: some search functions return indexes for all matches][see also: RegExIndex/RegExAll/StrSplit/StrCount] Prompt: MyLang, one-liner, input vars vText/vNeedle/vOcc (string/string/int), output var vPos (int). Does a string (vText) contain a substring (vNeedle), return the index of the nth (vOcc) match (occurrence). AutoHotkey: InStr [e.g. vPos := InStr(vText, vNeedle, 1,, vOcc)] [note: 1-based vPos, 1-based vOcc (occurrence), returns 0 if no match] [note: 3rd param sets case-sensitivity] C++: ___ C#: ___ Crystal: ___ Excel: ___ Excel VBA: ___ Go: ___ Java: ___ JavaScript: ___ [can use (RegEx, 3rd occurrence of 'abc', -1 if no match): vPos = vText.search(/(?<=(abc.*?){2})abc/)] Kotlin: ___ [can use (RegEx, findAll): vPos = Regex(vNeedle).findAll(vText).map{it.range.start}.toList().getOrElse(vOcc-1){-1}] [note: 0-based vPos, 1-based vOcc (occurrence), returns -1 if no match] PHP: ___ Python: ___ R: ___ Ruby: ___ Rust: ___ [can use: match_indices] Scala: ___ SQL (MySQL): ___ [can use (RegEx needle): regexp_instr(MyText, MyNeedle, 1, vOcc, 0, 'c')] SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: ___ [can use (RegEx): matches] UFL: StrStarts [or StrStartsWith][does string start with substring, return a bool][see also: StrEquals/StrContains/StrEnds] Prompt: MyLang, one-liner, input vars vText/vNeedle (strings), output var vIsMatch (bool). Does string vText start with substring vNeedle, return a bool. AutoHotkey: ___ [can use: vIsMatch := (SubStr(vText, 1, StrLen(vNeedle)) == vNeedle)] C++: starts_with [e.g. vIsMatch = vText.starts_with(vNeedle)] [also: strncmp/wcsncmp] C#: StartsWith [e.g. vIsMatch = vText.StartsWith(vNeedle)] Crystal: starts_with [e.g. vIsMatch = vText.starts_with?(vNeedle)] Excel: ___ [can use: =EXACT(LEFT(A1,LEN(MyNeedle)),MyNeedle)] Excel VBA: ___ [can use: vIsMatch = (Left(vText, Len(vNeedle)) = vNeedle)] Go: strings.HasPrefix [e.g. vIsMatch := strings.HasPrefix(vText, vNeedle)] Java: startsWith [e.g. vIsMatch = vText.startsWith(vNeedle)] JavaScript: startsWith [e.g. vIsMatch = vText.startsWith(vNeedle)] Kotlin: startsWith [e.g. vIsMatch = vText.startsWith(vNeedle)] PHP: str_starts_with [e.g. $vIsMatch = str_starts_with($vText, $vNeedle)] Python: str.startswith [e.g. vIsMatch = vText.startswith(vNeedle)] R: startsWith [e.g. vIsMatch = startsWith(vText, vNeedle)] Ruby: start_with [e.g. vIsMatch = vText.start_with?(vNeedle)] Rust: starts_with [e.g. vIsMatch = vText.starts_with(vNeedle)] Scala: startsWith [e.g. vIsMatch = vText.startsWith(vNeedle)] SQL (MySQL): ___ [can use: left(MyText, char_length(MyNeedle)) = BINARY MyNeedle] [also: substr(MyText, 1, char_length(MyNeedle)) = BINARY MyNeedle] [also (case-sensitivity depends on collation): MyText LIKE MyNeedle || '%'] [note (LIKE): % matches 0 or more chars, _ matches 1 char] [WARNING: LIKE: the needle may contain wildcards] [requires (||): set sql_mode=PIPES_AS_CONCAT] SQL (PostgreSQL): starts_with [e.g. starts_with(MyText, MyNeedle)] [also: MyText ^@ MyNeedle] [also: left(MyText, length(MyNeedle)) = MyNeedle] [also: substr(MyText, 1, length(MyNeedle)) = MyNeedle] [also: MyText LIKE MyNeedle || '%'] [also (escape wildcards): MyText LIKE replace(replace(MyText, '%', '\%'), '_', '\_') || '%'] [note (LIKE): % matches 0 or more chars, _ matches 1 char] [WARNING: LIKE: the needle may contain wildcards] [WARNING: if standard_conforming_strings is off, '\' must be doubled] SQL (SQLite): ___ [can use: substr(MyText, 1, length(MyText)) == MyNeedle] [also: glob(MyNeedle || '*', MyText)] [also (case-insensitive for ASCII letters, A-Za-z): like(MyNeedle || '%', MyText)] [note (LIKE): % matches 0 or more chars, _ matches 1 char] [WARNING: glob/like: the needle may contain wildcards] Swift: hasPrefix [e.g. vIsMatch = vText.hasPrefix(vNeedle)] UFL: StrEnds [or StrEndsWith][does string end with substring, return a bool][see also: StrEquals/StrContains/StrStarts] Prompt: MyLang, one-liner, input vars vText/vNeedle (strings), output var vIsMatch (bool). Does string vText end with substring vNeedle, return a bool. AutoHotkey: ___ [can use: vIsMatch := (SubStr(vText, -StrLen(vNeedle)) == vNeedle)] [note: AHK v1: vIsMatch := (SubStr(vText, -StrLen(vNeedle)+1) == vNeedle)] [also: vIsMatch := (SubStr(vText, StrLen(vText)+1-StrLen(vNeedle)) == vNeedle)] C++: ends_with [e.g. vIsMatch = vText.ends_with(vNeedle)] C#: EndsWith [e.g. vIsMatch = vText.EndsWith(vNeedle)] Crystal: ends_with [e.g. vIsMatch = vText.ends_with?(vNeedle)] Excel: ___ [can use: =EXACT(RIGHT(A1,LEN(MyNeedle)),MyNeedle)] Excel VBA: ___ [can use: vIsMatch = (Right(vText, Len(vNeedle)) = vNeedle)] Go: strings.HasSuffix [e.g. vIsMatch := strings.HasSuffix(vText, vNeedle)] Java: endsWith [e.g. vIsMatch = vText.endsWith(vNeedle)] JavaScript: endsWith [e.g. vIsMatch = vText.endsWith(vNeedle)] Kotlin: endsWith [e.g. vIsMatch = vText.endsWith(vNeedle)] PHP: str_ends_with [e.g. $vIsMatch = str_ends_with($vText, $vNeedle)] Python: str.endswith [e.g. vIsMatch = vText.endswith(vNeedle)] R: endsWith [e.g. vIsMatch = endsWith(vText, vNeedle)] Ruby: end_with [e.g. vIsMatch = vText.end_with?(vNeedle)] Rust: ends_with [e.g. vIsMatch = vText.ends_with(vNeedle)] Scala: endsWith [e.g. vIsMatch = vText.endsWith(vNeedle)] SQL (MySQL): ___ [can use: right(MyText, char_length(MyNeedle)) = BINARY MyNeedle] [also: substr(MyText, -char_length(MyNeedle)) = BINARY MyNeedle] [also (case-sensitivity depends on collation): MyText LIKE '%' || MyNeedle] [note (LIKE): % matches 0 or more chars, _ matches 1 char] [WARNING: LIKE: the needle may contain wildcards] [requires (||): set sql_mode=PIPES_AS_CONCAT] SQL (PostgreSQL): ___ [can use: right(MyText, length(MyNeedle)) = MyNeedle] [also: substr(MyText, length(MyText)-length(MyNeedle)+1) = MyNeedle] [also: MyText LIKE '%' || MyNeedle] [also (escape wildcards): MyText LIKE '%' || replace(replace(MyText, '%', '\%'), '_', '\_')] [note (LIKE): % matches 0 or more chars, _ matches 1 char] [WARNING: LIKE: the needle may contain wildcards] [WARNING: if standard_conforming_strings is off, '\' must be doubled] SQL (SQLite): ___ [can use: substr(MyText, -length(MyText)) == MyNeedle] [also: glob('*' || MyNeedle, MyText)] [also (case-insensitive for ASCII letters, A-Za-z): like('%' || MyNeedle, MyText)] [note (LIKE): % matches 0 or more chars, _ matches 1 char] [WARNING: glob/like: the needle may contain wildcards] Swift: hasSuffix [e.g. vIsMatch = vText.hasSuffix(vNeedle)] UFL: RegExNew [or StrToRegEx][string to RegEx object][note: some languages use 'RegEx', some use 'RegExp'][see also: StrIsAlnumRegExDemo] Prompt: MyLang, one-liner, input var vNeedle (int), output var oRegEx (object). String to RegEx object. AutoHotkey: ___ [note: RegEx needles stored as strings] C++: std::regex [e.g. creates a variable: std::regex oRegEx(vNeedle)] [requires: #include <regex>] C#: ___ [note: RegEx needles stored as strings] [requires: using System.Text.RegularExpressions] Crystal: Regex.new [e.g. oRegEx = Regex.new(vNeedle)] [also: e.g. oRegEx = /abc/] Excel: ___ Excel VBA: ___ [can use: Set oRegEx = CreateObject("VBScript.RegExp"): oRegEx.Pattern = vNeedle] Go: regexp.MustCompile [e.g. oRegEx := regexp.MustCompile(vNeedle)] [also: oRegEx, vErr := regexp.Compile(vNeedle)] [MAJOR WARNING: Go's RegEx lacks key features, e.g. \G \K (?=...) (?!...) (?<=...) (?<!...)] Java: Pattern.compile [e.g. Pattern oRegEx = Pattern.compile(vNeedle)] [note: some functions require strings not a pattern] [requires: import java.util.regex.Pattern] JavaScript: RegExp [e.g. oRegEx = new RegExp(vNeedle)] [e.g. oRegEx = new RegExp(vNeedle, vFlags)] [also: e.g. oRegEx = /abc/] [also: e.g. oRegEx = /abc/g] Kotlin: Regex [e.g. oRegEx = Regex(vNeedle)] [also: oRegEx = vNeedle.toRegex()] PHP: ___ [WARNING: RegEx needles stored as strings *with slashes*, e.g. "/abc/" not "abc"] Python: re.compile [e.g. oRegEx = re.compile(vNeedle)] [requires: import re] R: ___ [note: RegEx needles stored as strings] [MAJOR WARNING: various string functions do literal or RegEx manipulation depending on settings params, e.g. 'fixed=TRUE' (literal), e.g. 'perl=TRUE' (PCRE RegEx), e.g. omitted (typically 'extended' POSIX ERE RegEx)] Ruby: Regexp.new [e.g. oRegEx = Regexp.new(vNeedle)] [also: e.g. oRegEx = /abc/] Rust: Regex::new [e.g. oRegEx = Regex::new(vNeedle).unwrap()] [requires: use regex::Regex] [MAJOR WARNING: Rust's RegEx lacks key features, e.g. \G \K (?=...) (?!...) (?<=...) (?<!...)] Scala: r [e.g. oRegEx = vNeedle.r] [also: oRegEx = Regex(vNeedle)] [note: some functions require strings not a pattern] [requires (Regex): import scala.util.matching.Regex] [note: can omit the import, and write it longhand: scala.util.matching.Regex(vNeedle)] SQL (MySQL): ___ [note: RegEx needles stored as strings] SQL (PostgreSQL): ___ [note: RegEx needles stored as strings] SQL (SQLite): ___ Swift: Regex [e.g. oRegEx = try Regex(vNeedle)] UFL: RegExSupport [state whether key RegEx features are supported][see also: RegExSupportQE/RegExSupportLookAround/RegExEqualsAnchorsDemo/RegExEqualsDollarSignDemo] Prompt: MyLang. State whether RegEx features '\G' and '\K' are supported. AutoHotkey: ___ [note: supports \G and \K] C++: ___ [WARNING: doesn't support \G or \K] C#: ___ [WARNING: doesn't support \K] [note: supports \G] [workaround (\K): full support for look-behinds] Crystal: ___ [note: supports \G and \K] Excel: ___ Excel VBA: ___ [WARNING: VBScript.RegExp: doesn't support \G or \K] Go: ___ [WARNING: doesn't support \G or \K] Java: ___ [WARNING: doesn't support \K] [note: supports \G] JavaScript: ___ [WARNING: doesn't support \G or \K] [workaround (\G): use 'y', sticky flag] [workaround (\K): full support for look-behinds] Kotlin: ___ [WARNING: doesn't support \K] [note: supports \G] PHP: ___ [note: 'preg_' functions: support \G and \K] Python: ___ [WARNING: doesn't support \G or \K] R: ___ [note: when specify 'perl=TRUE': supports \G and \K] Ruby: ___ [note: supports \G and \K] Rust: ___ [WARNING: doesn't support \G or \K] Scala: ___ [WARNING: doesn't support \K] [note: supports \G] SQL (MySQL): ___ [WARNING: doesn't support \G or \K] SQL (PostgreSQL): ___ [WARNING: doesn't support \G or \K] [workaround (\K): full support for look-behinds] SQL (SQLite): ___ Swift: ___ [WARNING: doesn't support \G or \K] UFL: RegExSupportLookAround [state whether look-arounds are supported (i.e. look-behinds and look-aheads)][i.e. (?=...) (?!...) (?<=...) (?<!...)][e.g. test look-ahead: regexp_like('abcdef1', 'abc(?=.*\d)')][e.g. test look-behind: regexp_like('1abcdef', '(?<=\d.*)def')] Prompt: MyLang. State whether RegEx look-arounds are supported, i.e. (?=...) (?!...) (?<=...) (?<!...). State whether it supports variable-width look-behinds. AutoHotkey: ___ [note: look-aheads yes, look-behinds partial] [also: supports \K] C++: ___ [MAJOR WARNING: look-aheads only] C#: ___ [note: full support] Crystal: ___ [note: look-aheads yes, look-behinds partial] [also: supports \K] Excel: ___ Excel VBA: ___ [MAJOR WARNING: VBScript.RegExp: look-aheads only] Go: ___ [MAJOR WARNING: no support] Java: ___ [note: look-aheads yes, look-behinds partial] JavaScript: ___ [note: full support] Kotlin: ___ [note: look-aheads yes, look-behinds partial] PHP: ___ [note: 'preg_' functions: look-aheads yes, look-behinds partial] [also: 'preg_' functions: support \K] Python: ___ [note: look-aheads yes, look-behinds partial] R: ___ [note: when specify 'perl=TRUE': look-aheads yes, look-behinds partial] [also: when specify 'perl=TRUE': supports \K] Ruby: ___ [note: look-aheads yes, look-behinds partial] [also: supports \K] Rust: ___ [MAJOR WARNING: no support] Scala: ___ [note: look-aheads yes, look-behinds partial] SQL (MySQL): ___ [note: look-aheads yes, look-behinds partial] SQL (PostgreSQL): ___ [note: full support] SQL (SQLite): ___ Swift: ___ [MAJOR WARNING: look-aheads only] UFL: RegExSupportQE [state whether RegEx features '\Q' and '\E' are supported][they treat text literally, but literal '\E' must be escaped as '\\E'] Prompt: MyLang. State whether RegEx features '\Q' and '\E' are supported. AutoHotkey: ___ [note: supports \Q \E] C++: ___ [WARNING: std::regex doesn't support \Q \E] [note: std::regex::extended and std::regex::awk do support \Q \E] C#: ___ [WARNING: doesn't support \Q \E] Crystal: ___ [note: supports \Q \E] Excel: ___ Excel VBA: ___ [WARNING: VBScript.RegExp: doesn't support \Q \E] Go: ___ [WARNING: doesn't support \Q \E] Java: ___ [note: supports \Q \E] JavaScript: ___ [WARNING: doesn't support \Q \E] Kotlin: ___ [note: supports \Q \E] PHP: ___ [note: 'preg_' functions: support \Q \E] Python: ___ [WARNING: doesn't support \Q \E] R: ___ [note: when specify 'perl=TRUE': supports \Q \E] Ruby: ___ [note: supports \Q \E] Rust: ___ [WARNING: doesn't support \Q \E] Scala: ___ [note: supports \Q \E] SQL (MySQL): ___ [WARNING: doesn't support \Q \E] SQL (PostgreSQL): ___ [WARNING: doesn't support \Q \E] SQL (SQLite): ___ [WARNING: doesn't support \Q \E] Swift: ___ [WARNING: doesn't support \Q \E] UFL: RegExEscape [or StrEscape/RegExLiteral/RegExMakeLiteral][add escape characters to treat all characters literally, rather than treat some as metacharacters][workarounds: prepend chars (a hardcoded list or '[[:punct:]]') with '\', use '\Q' and '\E'][e.g. '$12.34' to '\$12\.34' or '\Q$12.34\E'][note: 12 chars that need escaping: '$()*+.?[\^{|'][note: 4 chars that need escaping in a character class: '-\]^'][see also: RegExSupport] Prompt: MyLang, one-liner, input var vNeedle (string), output var vNeedleRx (string). String to RegEx string, add escape characters to treat all characters literally. AutoHotkey: ___ [can use: vNeedleRx := RegExReplace(vNeedle, "[$()*+.?[\\^{|]", "\$0")] [also (\Q \E): vNeedleRx := "\Q" RegExReplace(vNeedle, "\\E", "\E\\E\Q") "\E"] [also (escapes more chars than necessary): vNeedleRx := RegExReplace(vNeedle, "[[:punct:]]", "\$0")] C++: ___ [can use: vNeedleRx = std::regex_replace(vNeedle, std::regex(R"(([$()*+.?[\\^{|]))"), R"(\$1)")] C#: Regex.Escape [e.g. vNeedleRx = System.Text.RegularExpressions.Regex.Escape(vNeedle)] Crystal: Regex.escape [e.g. vNeedleRx = Regex.escape(vNeedle)] [also: vNeedle.dump] [also: vNeedle.inspect] Excel: ___ Excel VBA: ___ [can use: Set oRegEx = CreateObject("VBScript.RegExp"): oRegEx.Pattern = "[$()*+.?[\\^{|]": oRegEx.Global = True: vNeedleRx = oRegEx.Replace(vNeedle, "\$&")] Go: regexp.QuoteMeta [e.g. vNeedleRx := regexp.QuoteMeta(vNeedle)] Java: Pattern.quote [e.g. vNeedleRx = Pattern.quote(vNeedle)] [requires: import java.util.regex.Pattern] JavaScript: RegExp.escape [e.g. vNeedleRx = RegExp.escape(vNeedle)] [also: vNeedleRx = vNeedle.replace(/[$()*+.?[\\^{|]/g, "\\$&")] Kotlin: Regex.escape [e.g. vNeedleRx = Regex.escape(vNeedle)] [also (returns an object): oRegEx = Regex.fromLiteral(vNeedle).pattern] PHP: preg_quote [e.g. $vNeedleRx = preg_quote($vNeedle)] Python: re.escape [e.g. vNeedleRx = re.escape(vNeedle)] R: ___ [can use: vNeedleRx = gsub(r"(([$()*+.?[\\^{|]))", r"(\\\1)", vNeedle)] [also (without raw strings): vNeedleRx = gsub("([$()*+.?[\\\\^{|])", "\\\\\\1", vNeedle)] [also (\Q \E): vNeedleRx = paste0("\\Q", gsub("\\E", "\\E\\\\E\\Q", vNeedle, fixed=TRUE), "\\E")] [note: R's string/RegEx functions typically accept 'fixed=TRUE', to treat strings literally, not as RegEx] [note: '\\\\\\1' becomes '\\\1', i.e. '\\' and '\1', literal backslash and backreference] Ruby: Regexp.escape [e.g. vNeedleRx = Regexp.escape(vNeedle)] [also: vNeedle.dump] [also: vNeedle.inspect] [alias (Regexp.escape): Regexp.quote] Rust: regex::escape [e.g. vNeedleRx = regex::escape(vNeedle)] Scala: Regex.quote [e.g. vNeedleRx = Regex.quote(vNeedle)] [requires: import scala.util.matching.Regex] [note: can omit the import, and write it longhand: vNeedleRx = scala.util.matching.Regex.quote(vNeedle)] SQL (MySQL): ___ [can use: regexp_replace(MyNeedle, '([$()*+.?\\[\\\\^{|])', '\\\\$1')] [WARNING: in MySQL, '[' requires escaping in a character class] SQL (PostgreSQL): ___ [can use: regexp_replace(MyNeedle, '[$()*+.?[\\^{|]', '\\\&', 'g')] SQL (SQLite): ___ Swift: NSRegularExpression.escapedPattern [e.g. vNeedleRx = NSRegularExpression.escapedPattern(for:vNeedle)] UFL: RegExIndex [or RegExMatchIndex][get the offset of the first match][note: match objects often contain an index and the matching substring][WARNING: languages may use 0-based/1-based string indexes][see also: RegExContains] Prompt: MyLang, one-liner, input vars vText/oRegEx (string/object), output var vPos (int). Does a string (vText) contain a RegEx needle (oRegEx), vPos is the index of the first match. AutoHotkey: RegExMatch [e.g. vPos := RegExMatch(vText, vNeedle)] [also (~=): vPos := vText ~= vNeedle] [note: 1-based, returns 0 if no match] C++: std::regex_search [e.g. std::smatch oMatch; auto vIsMatch = std::regex_search(vText, oMatch, oRegEx); auto vPos = vIsMatch ? oMatch.prefix().length() : -1;] [also (whole-string match): std::regex_match()] [requires (regex_search): #include <regex>] C#: Match [e.g. var oMatch = Regex.Match(vText, vNeedle); var vPos = oMatch.Success ? oMatch.Index : -1;] [WARNING: Regex.Match(vText, vNeedle).Index returns 0 if no match, and also 0 if the start of the string matches] [requires: using System.Text.RegularExpressions] Crystal: index [e.g. vPos = vText.index(oRegEx)] [also: vPos = vText =~ oRegEx] [note: returns nil if no match] Excel: ___ [can use: very limited functionality: COUNTIF() and COUNTIFS() accept strings with wildcards] Excel VBA: ___ [can use: Set oRegEx = CreateObject("VBScript.RegExp"): oRegEx.Pattern = vNeedle: If oRegEx.Test(vText) Then vPos = oRegEx.Execute(vText)(0).FirstIndex Else vPos = 0] [note: 1-based] [also: the LIKE operator (some RegEx-like features), and InStr()] Go: FindStringIndex [e.g. oPos := oRegEx.FindStringIndex(vText)] [afterwards: vTextNew := vText[oPos[0]:oPos[1]]] [note: returns nil if no match] Java: find [e.g. Matcher oMatcher = oRegEx.matcher(vText); var vIsMatch = oMatcher.find(); var vPos = vIsMatch ? oMatcher.start() : -1;] [requires: import java.util.regex.Matcher] JavaScript: search [e.g. vPos = vText.search(oRegEx)] [note: returns -1 if no match] Kotlin: find [e.g. var oMatch = oRegEx.find(vText); var vPos = if (oMatch != null) oMatch.range.start else -1] [note: find() returns null if no match] [also: containsMatchIn()/contains()] PHP: preg_match [e.g. preg_match($vNeedle, $vText, $oMatch, PREG_OFFSET_CAPTURE)] [afterwards (returns offset of first match, else null if no match): $vPos = $oMatch[0][1]] [also: mb_ereg_match] [note: 'preg' = Perl, 'ereg' = POSIX] Python: re.search [e.g. vPos = oRegEx.search(vText).start()] [note: search() returns None if no match] R: regexpr [e.g. vPos = regexpr(vNeedle, vText)[1]] [note: 1-based, returns -1 if no match] [also: regexec() also returns parenthesised sub-expression locations] Ruby: index [e.g. vPos = vText.index(oRegEx)] [also: vPos = vText =~ oRegEx] [note: returns nil if no match] Rust: find [e.g. oMatch = oRegEx.find(vText)] [e.g. vIsMatch = oMatch.is_some()] [e.g. vPos = oMatch.map_or(-1, |v| v.start() as i32)] [note: offsets are in bytes] Scala: findAllIn [e.g. var oMatchIter = oRegEx.findAllIn(vText); var vIsMatch = oMatchIter.hasNext; var vPos = if (vIsMatch) oMatchIter.start else -1] SQL (MySQL): regexp_instr [e.g. regexp_instr(MyText, MyNeedle, 1, 1, 0, 'c')] [WARNING: regexp_like() is case-insensitive by default, use 'c' for case-sensitive] [note: 1-based, returns 0 if no match] [note: use 'return_option' 1 to return the index after the match] [note: params: REGEXP_INSTR(expr, pat, pos, occurrence, return_option, match_type)] SQL (PostgreSQL): regexp_instr [e.g. regexp_instr(MyText, MyNeedle)] [note: 1-based, returns 0 if no match] [note: use 'endoption' 1 to return the index after the match] [note: can specify param 'N' to get the nth occurrence] SQL (SQLite): ___ Swift: firstMatch [e.g. var oMatch = try oRegEx.firstMatch(in:vText); var vPos = (oMatch != nil) ? vText.distance(from:vText.startIndex, to:oMatch!.range.lowerBound) : -1] UFL: (RegExIndexDemo) [or RegExMatchIndexDemo][RegEx match demo: return 0-based offset of first match, or return -1 if no match] Prompt: MyLang, one-liner, input vars vText/oRegEx (string/object), output var vPos (int). For haystack vText and RegEx needle oRegEx, vPos is the 0-based index of the first match, or -1 if no match. AutoHotkey: RegExMatch [e.g. vPos := -1 + RegExMatch(vText, vNeedle)] [note: -1 to convert 1-based to 0-based] C++: std::regex_search [e.g. std::regex oRegEx(vNeedle); std::smatch oMatch; auto vIsMatch = std::regex_search(vText, oMatch, oRegEx); auto vPos = oMatch.prefix().length() - !vIsMatch;] [also (whole-string match): std::regex_match()] [requires (regex_search): #include <regex>] C#: Match [e.g. var oMatch = Regex.Match(vText, vNeedle); var vPos = oMatch.Index - (oMatch.Success ? 0 : 1);] [WARNING: Regex.Match(vText, vNeedle).Index returns 0 if no match, and also 0 if the start of the string matches] [requires: using System.Text.RegularExpressions] Crystal: index [e.g. vPos = vText.index(oRegEx) || -1] [note: 0 is truthy in Crystal, so is maintained] Excel: ___ Excel VBA: ___ [can use: Set oRegEx = CreateObject("VBScript.RegExp"): oRegEx.Pattern = vNeedle: If oRegEx.Test(vText) Then vPos = -1 + oRegEx.Execute(vText)(0).FirstIndex Else vPos = -1] Go: ___ [note: Go lacks a ternary operator] Java: find [e.g. Pattern oRegEx = Pattern.compile(vNeedle); Matcher oMatcher = oRegEx.matcher(vText); var vPos = oMatcher.find() ? oMatcher.start() : -1;] [requires: import java.util.regex.Matcher] [requires: import java.util.regex.Pattern] JavaScript: search [e.g. vPos = vText.search(oRegEx)] [note: returns -1 if no match] Kotlin: find [e.g. vPos = oRegEx.find(vText)?.range?.start ?: -1] PHP: preg_match [e.g. preg_match("/" . $vNeedle . "/", $vText, $oMatch, PREG_OFFSET_CAPTURE); $vPos = $oMatch[0][1] ?? -1;] Python: re.search [e.g. vPos = next((v.start() for v in [oRegEx.search(vText)] if v!=None), -1)] R: ___ [can use: vPos = max(regexpr(vNeedle, vText)[1]-1, -1)] [note: -1 to convert 1-based to 0-based] [note: -1 applied to -1 (no match) gives -2, max makes it -1 again (the other values are unaffected by max)] Ruby: index [e.g. vPos = vText.index(oRegEx) || -1] [note: 0 is truthy in Ruby, so is maintained] Rust: find [e.g. vPos = oRegEx.find(vText).map_or(-1, |v| v.start() as i32)] [note: offsets are in bytes] Scala: findAllIn [e.g. var oRegEx = vNeedle.r; var oMatchIter = oRegEx.findAllIn(vText); var vPos = if (oMatchIter.hasNext) oMatchIter.start else -1] SQL (MySQL): regexp_instr [e.g. -1 + regexp_instr(MyText, MyNeedle)] [note: -1 to convert 1-based to 0-based] SQL (PostgreSQL): regexp_instr [e.g. -1 + regexp_instr(MyText, MyNeedle)] [note: -1 to convert 1-based to 0-based] SQL (SQLite): ___ Swift: firstMatch [e.g. var oRegEx = try Regex(vNeedle); var oMatch = try oRegEx.firstMatch(in:vText); var vPos = (oMatch != nil) ? vText.distance(from:vText.startIndex, to:oMatch!.range.lowerBound) : -1] UFL: RegExContains [or RegExBool/RegExMatchBool][return a boolean, whether the RegEx contains a match or not][this includes needles such as '^.*\\z' or '^.*$' that match the entire string][see also: RegExIndex/StrIsAlnumRegExDemo] Prompt: MyLang, one-liner, input vars vText/oRegEx (string/object), output var vIsMatch (bool). vIsMatch is whether or not the haystack vText contains the RegEx needle (oRegEx). AutoHotkey: RegExMatch [e.g. vIsMatch := !!RegExMatch(vText, vNeedle)] [also (~=): vIsMatch := !!(vText ~= vNeedle)] [note (RegExMatch): 1-based, returns 0 if no match] C++: std::regex_search [e.g. std::smatch oMatch; auto vIsMatch = std::regex_search(vText, oMatch, oRegEx);] [note: can omit match_results param: e.g. vIsMatch = std::regex_search(vText, oRegEx)] [also (whole-string match): std::regex_match()] [requires (regex_search): #include <regex>] C#: Match [e.g. vIsMatch = Regex.Match(vText, vNeedle).Success] [e.g. var oMatch = Regex.Match(vText, vNeedle); var vIsMatch = oMatch.Success] Crystal: matches [e.g. vIsMatch = oRegEx.matches?(vText)] [also: vIsMatch = (vText.index(oRegEx) != nil)] [also: vIsMatch = ((vText =~ oRegEx) != nil)] [note: order interchangeable: oRegEx.matches?(vText) and vText.matches?(oRegEx)] Excel: ___ Excel VBA: ___ [can use: Set oRegEx = CreateObject("VBScript.RegExp"): oRegEx.Pattern = vNeedle: vIsMatch = oRegEx.Test(vText)] [also: the LIKE operator (some RegEx-like features)] Go: MatchString [e.g. vIsMatch := oRegEx.MatchString(vText)] Java: find [e.g. vIsMatch = oRegEx.matcher(vText).find()] [also (whole-string match): matches] JavaScript: test [e.g. vIsMatch = oRegEx.test(vText)] Kotlin: containsMatchIn [e.g. vIsMatch = oRegEx.containsMatchIn(vText)] [also: vIsMatch = (oRegEx.find(vText) != null)] PHP: preg_match [e.g. $vIsMatch = !!preg_match($vNeedle, $vText)] [also: mb_ereg_match] [note: 'preg' = Perl, 'ereg' = POSIX] Python: re.search [e.g. vIsMatch = (oRegEx.search(vText) != None)] R: grepl [e.g. vIsMatch = grepl(vNeedle, vText, perl=TRUE)] [note: uses 'extended' POSIX ERE RegEx if 'perl=TRUE' is omitted] Ruby: match [e.g. vIsMatch = oRegEx.match?(vText)] [also: vIsMatch = (vText.index(oRegEx) != nil)] [also: vIsMatch = ((vText =~ oRegEx) != nil)] [note: order interchangeable: oRegEx.match?(vText) and vText.match?(oRegEx)] Rust: is_match [e.g. vIsMatch = oRegEx.is_match(vText)] [also: vIsMatch = oRegEx.find(vText).is_some()] Scala: findFirstIn [e.g. vIsMatch = oRegEx.findFirstIn(vText).isDefined] SQL (MySQL): regexp_like [e.g. regexp_like(MyText, MyNeedle, 'c')] [WARNING: regexp_like() is case-insensitive by default, use 'c' for case-sensitive] [alias (regexp_like): MyText REGEXP MyNeedle, MyText RLIKE MyNeedle] [note: LIKE doesn't support character classes] SQL (PostgreSQL): regexp_like [e.g. regexp_like(MyText, MyNeedle)] [alias: MyText ~ MyNeedle, case-insensitive: MyText ~* MyNeedle] [also: LIKE (case-sensitive), ILIKE (case-insensitive), SIMILAR TO] [note: ~~ ~~* !~~ !~~* operators are equivalent LIKE/ILIKE/NOT LIKE/NOT ILIKE respectively] [e.g. LIKE: MyText LIKE '_abc%'] [note (LIKE): % matches 0 or more chars, _ matches 1 char] [WARNING: if standard_conforming_strings is off, '\' must be doubled] [note: LIKE doesn't support character classes] SQL (SQLite): ___ [can use: e.g. glob(MyNeedle, MyText)] [also: e.g. like(MyNeedle, MyText)] [WARNING: LIKE is case-insensitive for ASCII letters (A-Za-z)] [note (LIKE): % matches 0 or more chars, _ matches 1 char] [also: GLOB operator, LIKE operator] [WARNING: glob/like parameter order: 'glob(needle, haystack)' versus 'haystack GLOB needle', the same for LIKE] [e.g. like() with custom escape char: like('AaAa\%\_\\', 'AAaa%_\', '\')] [WARNING: glob/like: the haystack may contain wildcards] [MAJOR WARNING: differing wildcards and case-sensitivities: GLOB ?*[], LIKE _%] [note: LIKE doesn't support character classes, GLOB does] Swift: firstMatch [e.g. var oMatch = try oRegEx.firstMatch(in:vText); var vIsMatch = (oMatch != nil)] UFL: (RegExEquals) [or RegExMatchEntire/RegExMatchWhole][return a boolean, whether the RegEx matches the whole string (the entire string) or not][equivalent to RegExContains with '^myneedle\\z' (or sometimes '^myneedle$')][WARNING: not 'whole word match', for that, use RegEx '\bmyneedle\b'][see also: RegExEqualsAnchorsDemo/StrIsAlnumRegExDemo] Prompt: MyLang, one-liner, input vars vText/oRegEx (string/object), output var vIsMatch (bool). vIsMatch is whether or not the entirety of haystack vText matches the RegEx needle (oRegEx). AutoHotkey: ___ C++: std::regex_match [e.g. std::smatch oMatch; auto vIsMatch = std::regex_match(vText, oMatch, oRegEx);] [note: std::regex_match() (whole-string match) cf. std::regex_search()] [requires (regex_match): #include <regex>] C#: ___ Crystal: ___ Excel: ___ Excel VBA: ___ [can use: the LIKE operator (some RegEx-like features)] Go: ___ Java: matches [e.g. vIsMatch = "abc".matches("...")] [note: whole-string match] JavaScript: ___ Kotlin: matches [e.g. vIsMatch = "abc".matches(Regex("..."))] [also: vIsMatch = (Regex("...").matchEntire("abc") != null)] [note (both): whole-string match] PHP: ___ Python: re.fullmatch [e.g. vIsMatch = (re.fullmatch("...", "abc") != None)] R: ___ Ruby: ___ Rust: ___ Scala: ___ SQL (MySQL): ___ SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: wholeMatch [e.g. var oMatch = try oRegEx.wholeMatch(in:vText); var vIsMatch = (oMatch != nil)] UFL: RegExEqualsAnchorsDemo [or RegExMatchEndsDemo/RegExEndsDemo][demonstrate anchors that match the entire string 'abc', with no leading/trailing chars (e.g. '\n' or '\r' or '\r\n') permitted][e.g. try haystacks such as 'abc\n' and 'abc\r\n'][note: typically '\z' (or '\Z') does this, sometimes '$' does this (e.g. always strict, strict if a certain mode is set, always permissive)][WARNING: '\z' or '\\z' depending on how many escape chars are needed][see also: RegExContains/RegExEquals] Prompt: MyLang, one-liner, output var vIsMatch (bool). Demonstrate anchors that match the entire string 'abc', with no leading/trailing chars (e.g. '\n' or '\r' or '\r\n') permitted. The haystack is "abc". AutoHotkey: vIsMatch := RegExMatch("abc", "^abc\z")] [also ('$' with 'D' option): vIsMatch := RegExMatch("abc", "D)^abc$")] [note: '$' is strict if 'D' option (PCRE_DOLLAR_ENDONLY) is used] C++: vIsMatch = std::regex_search("abc", std::regex("^abc$")) [requires: #include <regex>] [note: '$' is strict] [note: lacks the '\z' anchor] C#: vIsMatch = Regex.Match("abc", "^abc\\z").Success [requires: using System.Text.RegularExpressions] Crystal: vIsMatch = /^abc\z/.matches?("abc") Excel: ___ Excel VBA: Set oRegEx = CreateObject("VBScript.RegExp"): oRegEx.Pattern = "^abc$": vIsMatch = oRegEx.Test("abc") [note: '$' is strict] [note: lacks the '\z' anchor] Go: vIsMatch := regexp.MustCompile("^abc\\z").MatchString("abc") [also ('$' is strict): vIsMatch := regexp.MustCompile("^abc$").MatchString("abc")] Java: vIsMatch = Pattern.compile("^abc\\z").matcher("abc").find() [requires: import java.util.regex.Pattern] JavaScript: vIsMatch = /^abc$/.test("abc") [note: '$' is strict] [note: lacks the '\z' anchor] Kotlin: vIsMatch = Regex("^abc\\z").containsMatchIn("abc") PHP: $vIsMatch = !!preg_match("/^abc\\z/", "abc") Python: vIsMatch = (re.compile("^abc\\Z").search("abc") != None) [WARNING: capital Z, not small z] [requires: import re] R: vIsMatch = grepl("^abc\\z", "abc", perl=TRUE) [also ('$' is strict, *without* 'perl=TRUE'): vIsMatch = grepl("^abc$", "abc")] [WARNING: '$' is *NOT* strict, with 'perl=TRUE'] [note: grepl() by default, without 'perl=TRUE', doesn't support the '\z' anchor] Ruby: vIsMatch = /^abc\z/.match?("abc") Rust: vIsMatch = Regex::new("^abc\\z").unwrap().is_match("abc") [also ('$' is strict): vIsMatch = Regex::new("^abc$").unwrap().is_match("abc")] [requires: use regex::Regex] Scala: vIsMatch = "^abc\\z".r.findFirstIn("abc").isDefined SQL (MySQL): regexp_like('abc', '^abc\\z') SQL (PostgreSQL): regexp_like('abc', '^abc$') [note: '$' is strict] [note: lacks the '\z' anchor] SQL (SQLite): ___ Swift: vIsMatch = (try Regex("^abc\\z").firstMatch(in:"abc") != nil) [also ('$' is strict): vIsMatch = (try Regex("^abc$").firstMatch(in:"abc") != nil)] UFL: (RegExEqualsDollarSignDemo) [or RegExEqualsNewlineDemo][for '$' (dollar sign), does it strictly mean the end of the string (or is a trailing linefeed permitted, e.g. '\n' or '\r' or '\r\n')][note: false means stricter (which is likely preferable), true means more permissive][see also: RegExContains/RegExEquals] Prompt: MyLang, one-liner, output var vIsMatch (bool). State whether or not '$' strictly means the end of the string (or is a trailing line break (newline) permitted, e.g. '\n' or '\r' or '\r\n'). As a comment show code that tests this e.g. JavaScript: vIsMatch = /^abc$/.test("abc\n"). AutoHotkey: ___ [true: vIsMatch := RegExMatch("abc`n", "^abc$")] [false ('D' for PCRE_DOLLAR_ENDONLY): vIsMatch := RegExMatch("abc`n", "D)^abc$")] [note: AHK v1/v2: both true for 'abc`r`n', AHK v2: true for 'abc`n', AHK v1: false for 'abc`n'] C++: ___ [false: vIsMatch = std::regex_search("abc\n", std::regex("^abc$"))] [requires: #include <regex>] C#: ___ [true: vIsMatch = Regex.Match("abc\n", "^abc$").Success] [requires: using System.Text.RegularExpressions] Crystal: ___ [true: vIsMatch = /^abc$/.matches?("abc\n")] Excel: ___ Excel VBA: ___ [can use: false: Set oRegEx = CreateObject("VBScript.RegExp"): oRegEx.Pattern = "^abc$": vIsMatch = oRegEx.Test("abc" & vbLf)] Go: ___ [false: vIsMatch := regexp.MustCompile("^abc$").MatchString("abc\n")] Java: ___ [true: vIsMatch = Pattern.compile("^abc$").matcher("abc\n").find()] [requires: import java.util.regex.Pattern] JavaScript: ___ [false: vIsMatch = /^abc$/.test("abc\n")] Kotlin: ___ [true: vIsMatch = Regex("^abc$").containsMatchIn("abc\n")] PHP: ___ [true: $vIsMatch = !!preg_match("/^abc$/", "abc\n")] Python: ___ [true: vIsMatch = (re.compile("^abc$").search("abc\n") != None)] [requires: import re] R: ___ [false: vIsMatch = grepl("^abc$", "abc\n")] [true (for 'perl=TRUE'): vIsMatch = grepl("^abc$", "abc\n", perl=TRUE)] Ruby: ___ [true: vIsMatch = /^abc$/.match?("abc\n")] Rust: ___ [false: vIsMatch = Regex::new("^abc$").unwrap().is_match("abc\n")] [requires: use regex::Regex] Scala: ___ [true: vIsMatch = "^abc$".r.findFirstIn("abc\n").isDefined] SQL (MySQL): ___ [true: regexp_like('abc\n', '^abc$')] SQL (PostgreSQL): ___ [false: regexp_like(E'abc\n', '^abc$')] SQL (SQLite): ___ Swift: ___ [false: vIsMatch = (try Regex("^abc$").firstMatch(in:"abc\n") != nil)] UFL: (RegExFirst) [or RegExMatchFirst][get text of first match][WARNING: languages may use 0-based/1-based string indexes][see also: RegExAll/RegExReplace/OpSafeNav] Prompt: MyLang, one-liner, input vars vText/oRegEx (string/object), output var vValue (string). For haystack vText and RegEx needle oRegEx, vValue is the text of the first match. AutoHotkey: ___ [can use: RegExReplace(), i.e. replace everything with a substring] C++: std::regex_search [e.g. std::smatch oMatch; bool vIsMatch = std::regex_search(vText, oMatch, oRegEx); std::string vValue = oMatch.str();] [requires: #include <regex>] C#: Match [e.g. oMatch = Regex.Match(vText, vNeedle)] [e.g. vIsMatch = oMatch.Success] [e.g. (Value is a blank string if no match): vValue = oMatch.Value] [requires (Regex): using System.Text.RegularExpressions] Crystal: match [e.g. oMatch = oRegEx.match(vText); vIsMatch = (oMatch == nil); vValue = oMatch.to_s] Excel: ___ Excel VBA: ___ [can use: Set oRegEx = CreateObject("VBScript.RegExp"): oRegEx.Pattern = vNeedle: Set oMatches = oRegEx.Execute(vText)] [e.g. vValue = oMatches(0).Value] [e.g. vIsMatch = oMatches.Count > 0] Go: FindString [e.g. vValue := oRegEx.FindString(vText)] [WARNING: returns blank if no match, and if match is a blank string, workaround to distinguish between the two: vIsMatch := (oRegEx.FindStringIndex(vText) != nil), another workaround (not mentioned by the documentation): vIsMatch := oRegEx.MatchString(vText)] [requires: import "regexp"] Java: find [e.g. oMatcher = oRegEx.matcher(vText)] [e.g. vIsMatch = oMatcher.find()] [e.g. vValue = vIsMatch ? oMatcher.group(0) : ""] [requires: import java.util.regex.Matcher] JavaScript: match [e.g. using the optional chaining operator: vValue = vText.match(oRegEx)?.[0] ?? ""] [also: vIsMatch = vText.match(oRegEx) != null] [note: match() returns a string array (or null if no matches)] Kotlin: find [e.g. (returns null if no match): oMatch = oRegEx.find(vText)] [e.g. vValue = oRegEx.find(vText)?.value ?: ""] [e.g. vIsMatch = (oRegEx.find(vText) == null)] PHP: preg_match [e.g. (can omit 'matches' param): $vIsMatch = preg_match($vNeedle, $vText, $oMatch)] [e.g. $vValue = $oMatch[0] ?? ""] Python: re.search [e.g. (returns None if no match): oMatch = re.search(oRegEx, vText)] [e.g. vValue = (oMatch or [""])[0]] [e.g. vIsMatch = (oMatch != None)] [requires: import re] R: ___ [can use: vValue = paste0("", regmatches(vText, regexpr(vNeedle, vText, perl=TRUE)))] [WARNING: regmatches() returns character(0) if no match (not ""), workaround: use paste0() to coerce character(0) to "" (which has no effect on other strings)] [note: uses 'extended' POSIX ERE RegEx if 'perl=TRUE' is omitted] Ruby: match [e.g. oMatch = oRegEx.match(vText); vIsMatch = (oMatch == nil); vValue = oMatch[0]] Rust: find [e.g. oMatch = oRegEx.find(vText)] [e.g. vIsMatch = oMatch.is_some()] [e.g. vValue = oMatch.map_or("", |v| v.as_str())] [also (longer alternative): vValue = if oMatch.is_some() {oMatch.unwrap().as_str()} else {""}] Scala: findFirstIn [e.g. oMatch = oRegEx.findFirstIn(vText)] [e.g. vIsMatch = oMatch.isDefined] [e.g. vValue = oMatch.getOrElse("")] SQL (MySQL): regexp_substr [e.g. regexp_substr(MyText, MyNeedle, 1, 1, 'c')] [WARNING: regexp_substr() is case-insensitive by default, use 'c' for case-sensitive] SQL (PostgreSQL): regexp_substr [e.g. regexp_substr(MyText, MyNeedle)] [note: can specify param 'N' to get the nth occurrence] SQL (SQLite): ___ Swift: firstMatch [e.g. oMatch = try oRegEx.firstMatch(in:vText)] [e.g. vIsMatch = (oMatch != nil)] [e.g. (using optional chaining operator): vValue = oMatch?.0 ?? ""] [also: vValue = oMatch!.0] UFL: RegExAll [or RegExMatchAll/RegExFindAll/RegExContainsAll][find all matches][e.g. return an array of substrings][e.g. 'abcdefghi' with needle '.{3}' gives ["abc","def","ghi"]] Prompt: MyLang, one-liner, input vars vText/oRegEx (string/object), output var oArray (array). For haystack vText and RegEx needle oRegEx, get all matches as a string array oArray. AutoHotkey: ___ [can use: repeated RegExMatch()] C++: ___ [can use: std::sregex_iterator (std::regex_iterator) and str() on each iteration] [also: repeated std::regex_search and (inefficiently) using suffix() on each iteration] [requires: #include <regex>] C#: Matches [e.g. oArray = Regex.Matches(vText, vNeedle).Select(v=>v.Value).ToArray()] [requires (Regex): using System.Text.RegularExpressions] [requires (Select): using System.Linq] Crystal: scan [e.g. oArray = vText.scan(oRegEx).map{|v| v.to_s}] Excel: ___ Excel VBA: ___ [can use: Set oRegEx = CreateObject("VBScript.RegExp"): oRegEx.Pattern = vNeedle: oRegEx.Global = True: Set oMatches = oRegEx.Execute(vText)] [e.g. vValue = oMatches(0).Value] Go: FindAllString [e.g. oSlice := oRegEx.FindAllString(vText, -1)] [also: repeated FindStringIndex] [requires: import "regexp"] Java: ___ [can use: String[] oArray = Pattern.compile(vNeedle).matcher(vText).results().map(MatchResult::group).toArray(String[]::new)] [also: repeated find()] [requires: import java.util.regex.Pattern] [requires: import java.util.regex.MatchResult] JavaScript: match [e.g. (the RegEx must use the global flag): oArray = vText.match(oRegEx) || []] [also (the RegEx must use the global flag): oArray = [...vText.matchAll(oRegEx)].map(v=>v[0])] [note: match() returns a string array (or null if no matches)] [note: matchAll() returns an iterator, e.g. key 0 contains a string] [also (the RegEx must use the global flag): repeated test(): lastIndex is the position after the last match: oRegEx.test(vText); vPos = oRegEx.lastIndex;] Kotlin: findAll [e.g. oArray = oRegEx.findAll(vText).map{it.groupValues[0]}.toList().toTypedArray()] PHP: preg_match_all [e.g. preg_match_all($vNeedle, $vText, $oArray)] Python: re.findall [e.g. oList = re.findall(oRegEx, vText)] [also: oList = [o[0] for o in re.finditer(oRegEx, vText)]] [also: re.split()] [requires: import re] R: ___ [can use: oVec = unlist(regmatches(vText, gregexpr(vNeedle, vText)))] [note (regmatches): returns an empty list if no matches] Ruby: scan [e.g. oArray = vText.scan(oRegEx)] Rust: find_iter [e.g. oVec = oRegEx.find_iter(vText).map(|v| v.as_str()).collect::<Vec<_>>()] Scala: ___ [can use: findAllIn once, and then repeated hasNext/next] [note: 'start' to get position, 'next' to get a matching string and advance by 1 item] SQL (MySQL): ___ SQL (PostgreSQL): regexp_matches [e.g. regexp_matches(MyText, MyNeedle, 'g')] SQL (SQLite): ___ Swift: ___ [can use: var oRegEx = try NSRegularExpression(pattern:vNeedle); var oMatch = oRegEx.matches(in:vText, range:NSRange(vText.startIndex..., in:vText)); var oArray = oMatch.map{String(vText[Range($0.range, in:vText)!])}] [requires: import Foundation] UFL: RegExIndexAll [or RegExMatchIndexAll/RegExFindIndexAll][find all matches][e.g. return an array of indexes (and possibly lengths)][e.g. 'abcdefghi' with needle '.{3}' gives 0-based indexes [0,3,6]][WARNING: languages may use 0-based/1-based string indexes] Prompt: MyLang, one-liner, input vars vText/oRegEx (string/object), output var oArray (array). For haystack vText and RegEx needle oRegEx, get the indexes for all matches as an int array. AutoHotkey: ___ [can use: repeated RegExMatch()] C++: ___ [can use: std::sregex_iterator (std::regex_iterator) and position() on each iteration] [requires: #include <regex>] C#: Matches [e.g. oArray = Regex.Matches(vText, vNeedle).Select(v=>v.Index).ToArray()] [requires (Regex): using System.Text.RegularExpressions] [requires (Select): using System.Linq] Crystal: scan [e.g. oArray = vText.scan(oRegEx).map{|v| v.begin}] Excel: ___ Excel VBA: ___ [can use: Set oRegEx = CreateObject("VBScript.RegExp"): oRegEx.Pattern = vNeedle: oRegEx.Global = True: Set oMatches = oRegEx.Execute(vText)] [e.g. vPos = oMatches(0).FirstIndex] [note: 1-based] Go: FindAllStringIndex [e.g. oSlice := oRegEx.FindAllStringIndex(vText, -1)] [WARNING: returns a slice of slices (start/end indexes), not a slice of start indexes] [requires: import "regexp"] Java: ___ [can use: int[] oArray = Pattern.compile(vNeedle).matcher(vText).results().map(MatchResult::start).mapToInt(v->v).toArray()] [also: Integer[] oArray = Pattern.compile(vNeedle).matcher(vText).results().map(MatchResult::start).toArray(Integer[]::new)] [also: repeated find()] [requires: import java.util.regex.Pattern] [requires: import java.util.regex.MatchResult] JavaScript: matchAll [e.g. (the RegEx must use the global flag): oArray = [...vText.matchAll(oRegEx)].map(v=>v.index)] [note: matchAll returns an iterator, e.g. property 'index' contains a position] Kotlin: findAll [e.g. oArray = oRegEx.findAll(vText).map{it.range.start}.toList().toTypedArray()] PHP: preg_match_all [e.g. preg_match_all($vNeedle, $vText, $oMatch, PREG_OFFSET_CAPTURE)] [afterwards: $oArray = array_map(fn($v)=>$v[1], $oMatch[0])] Python: re.finditer [also: oList = [o.start() for o in re.finditer(oRegEx, vText)]] [requires: import re] R: gregexpr [e.g. oVec = unlist(gregexpr(vNeedle, vText, perl=TRUE)); oVec = `if`(oVec[1]!=-1, oVec, integer(0))] [WARNING: gregexpr() returns -1 (as the vector within the output list) if no matches] [note: uses 'extended' POSIX ERE RegEx if 'perl=TRUE' is omitted] [also: gregexec() also returns parenthesised sub-expression locations] Ruby: ___ [can use: oArray = []; vText.scan(oRegEx){oArray << Regexp.last_match.offset(0)[0]}] [also: oArray = []; vText.scan(oRegEx){oArray << $~.offset(0)[0]}] Rust: find_iter [e.g. oVec = oRegEx.find_iter(vText).map(|v| v.start()).collect::<Vec<_>>()] Scala: ___ [can use: findAllIn once, and then repeated hasNext/next] [note: 'start' to get position, 'next' to get a matching string and advance by 1 item] SQL (MySQL): ___ SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: ___ [can use: var oRegEx = try NSRegularExpression(pattern:vNeedle); var oMatch = oRegEx.matches(in:vText, range:NSRange(vText.startIndex..., in:vText)); var oArray = oMatch.map{vText.distance(from:vText.startIndex, to:Range($0.range, in:vText)!.lowerBound)}] [requires: import Foundation] UFL: RegExReplace [or RegExReplaceAll][replace all matches][perhaps with an option to replace the first n matches][see also: StrTranslate/StrReplaceMult] Prompt: MyLang, one-liner, input vars vText/oRegEx/vAfter (string/object/string), output var vTextNew (string). Replace all occurrences of oRegEx and output to vTextNew. AutoHotkey: RegExReplace [e.g. vTextNew := RegExReplace(vText, vNeedle, vAfter)] C++: std::regex_replace [e.g. std::string vTextNew = std::regex_replace(vText, oRegEx, vAfter)] [requires: #include <regex>] C#: Regex.Replace [e.g. vTextNew = Regex.Replace(vText, vNeedle, vAfter)] [requires: using System.Text.RegularExpressions] Crystal: gsub [e.g. vTextNew = vText.gsub(oRegEx, vAfter)] [also (replace using hash map, prioritise longer key names): vTextNew = vText.gsub(oMap.to_a.sort_by{|k,v|-k.size}.to_h)] [also: for a single replacement: sub()] Excel: ___ Excel VBA: ___ [can use: Set oRegEx = CreateObject("VBScript.RegExp"): oRegEx.Pattern = vNeedle: oRegEx.Global = True: vTextNew = oRegEx.Replace(vText, vAfter)] Go: ReplaceAllString [e.g. vTextNew := oRegEx.ReplaceAllString(vText, vAfter)] [also: ReplaceAllStringFunc/ReplaceAllLiteralString] [requires: import "regexp"] [also (single pass): vTextNew := strings.NewReplacer(vBefore1, vAfter1, vBefore2, vAfter2, vBefore3, vAfter3).Replace(vText)] Java: replaceAll [e.g. vTextNew = vText.replaceAll(vNeedle, vAfter)] JavaScript: replaceAll [e.g. (the RegEx must use the global flag): vTextNew = vText.replaceAll(oRegEx, vAfter)] [also: replace()] [note: replaceAll() throws if the RegEx lacks the global flag, whereas replace() does one replacement max] Kotlin: replace [e.g. vTextNew = vText.replace(oRegEx, vAfter)] PHP: preg_replace [e.g. $vTextNew = preg_replace($vNeedle, $vAfter, $vText)] [also: mb_ereg_replace] [note: 'preg' = Perl, 'ereg' = POSIX] [e.g. prepare needle: $vNeedle = "/" . $vNeedle . "/"] Python: re.sub [e.g. vTextNew = re.sub(oRegEx, vAfter, vText)] [requires: import re] R: gsub [e.g. vTextNew = gsub(vNeedle, vAfter, vText)] [note (gsub): RegEx by default, use 'fixed=TRUE' for literal string replacement] [also: for a single replacement: sub()] Ruby: gsub [e.g. vTextNew = vText.gsub(oRegEx, vAfter)] [also (replace using hash maps, prioritise longer key names): vTextNew = vText.gsub(Regexp.union(oMap.keys.sort_by{|k|-k.length}), oMap)] [also: for a single replacement: sub()] Rust: replace_all [e.g. vTextNew = oRegEx.replace_all(vText, vAfter)] [e.g. prepare needle: oRegEx = Regex::new(vNeedle).unwrap()] Scala: replaceAllIn [e.g. oRegEx.replaceAllIn(vText, vAfter)] SQL (MySQL): regexp_replace [e.g. regexp_replace(MyText, MyBefore, MyAfter, 1, 0, 'c')] [WARNING: regexp_replace() is case-insensitive by default, use 'c' for case-sensitive] SQL (PostgreSQL): regexp_replace [e.g. regexp_replace(MyText, MyBefore, MyAfter, 1, 0)] [note: can specify param 'N' to replace the nth occurrence] SQL (SQLite): ___ Swift: replacingOccurrences [e.g. vTextNew = vText.replacingOccurrences(of:vNeedle, with:vAfter, options:.regularExpression)] [also: vTextNew = oRegEx.stringByReplacingMatches(in:vText, range:NSMakeRange(0,vText.count), withTemplate:vAfter)] [also: stringByReplacingMatchesInString()] [requires (replacingOccurrences): import Foundation] UFL: RegExPartsDemo [demonstrate syntax for a RegEx replace with capture groups][the overall match capture group is typically one of: '$&', '$0', '\&', '\0'][further capture groups are typically 1-based, e.g. starting at '$1' or '\1'][the demo code replaces a string with itself and its first 3 chars, all space-separated, e.g. 'abcde' to 'abcde a b c'] Prompt: MyLang, one-liner, output var vText (string). Demonstrate syntax for a RegEx replace with capture groups, equivalent to JavaScript: vText = "abcde".replace(/^(.)(.)(.).*$/, "$& $1 $2 $3"). Expected output: 'abcde a b c'. AutoHotkey: vText := RegExReplace("abcde", "^(.)(.)(.).*$", "$0 $1 $2 $3") [note: '$&' doesn't work] [also: '$U1'/'$T1'/'$L1' syntax, for upper/title/lower case respectively: e.g. '$U1 and $U{1} transcribe an uppercase version of the first subpattern'] C++: vText = std::regex_replace("abcde", std::regex("^(.)(.)(.).*$"), "$& $1 $2 $3") [note: '$0' also works] [requires: #include <regex>] C#: vText = Regex.Replace("abcde", "^(.)(.)(.).*$", "$& $1 $2 $3") [note: '$0' also works] [requires: using System.Text.RegularExpressions] Crystal: vText = "abcde".gsub(/^(.)(.)(.).*$/, "\\0 \\1 \\2 \\3") [also: vText = "abcde".gsub(/^(.)(.)(.).*$/, %q(\0 \1 \2 \3))] [note: '\&' doesn't work] Excel: ___ Excel VBA: Set oRegEx = CreateObject("VBScript.RegExp"): oRegEx.Pattern = "^(.)(.)(.).*$": vText = oRegEx.Replace("abcde", "$& $1 $2 $3") [note: '$0' doesn't work] Go: vText := regexp.MustCompile(`^(.)(.)(.).*$`).ReplaceAllString("abcde", "$0 $1 $2 $3") [note: '$&' doesn't work] Java: vText = "abcde".replaceAll("^(.)(.)(.).*$", "$0 $1 $2 $3") [note: '$&' doesn't work] JavaScript: vText = "abcde".replace(/^(.)(.)(.).*$/, "$& $1 $2 $3") [note: '$0' doesn't work] Kotlin: vText = "^(.)(.)(.).*$".toRegex().replace("abcde", "$0 $1 $2 $3") [note: '$&' doesn't work] PHP: $vText = preg_replace("/^(.)(.)(.).*$/", "$0 $1 $2 $3", "abcde") [also (note: '\' instead of '&', and single quotes): $vText = preg_replace("/^(.)(.)(.).*$/", '\0 \1 \2 \3', "abcde")] [note: '$&' and '\&' don't work] Python: vText = re.sub("^(.)(.)(.).*$", r"\g<0> \1 \2 \3", "abcde") [note: '\g<&>' doesn't work] [requires: import re] R: ___ [can use: vText = gsub("^((.)(.)(.).*)$", "\\1 \\2 \\3 \\4", "abcde")] [WARNING: R lacks '\0' or '\&' overall match syntax, workaround: add parentheses around the entire expression, and increase the capture group indexes by 1] Ruby: vText = "abcde".gsub(/^(.)(.)(.).*$/, '\0 \1 \2 \3') [note: single quotes] [note: '\&' also works] [note: sub() would also work for this example] Rust: vText = regex::Regex::new("^(.)(.)(.).*$").unwrap().replace("abcde", "$0 $1 $2 $3") [note: '$&' doesn't work] Scala: vText = "^(.)(.)(.).*$".r.replaceAllIn("abcde", m => s"${m.matched} ${m.group(1)} ${m.group(2)} ${m.group(3)}") SQL (MySQL): SELECT regexp_replace('abcde', '^(.)(.)(.).*$', '$0 $1 $2 $3') [note: '$&' doesn't work] SQL (PostgreSQL): SELECT regexp_replace('abcde', '^(.)(.)(.).*$', '\& \1 \2 \3') [note: '\0' doesn't work] SQL (SQLite): ___ Swift: vText = "abcde".replacingOccurrences(of:"^(.)(.)(.).*$", with:"$0 $1 $2 $3", options:.regularExpression) [note: '$&' doesn't work] [requires: import Foundation] UFL: (RegExCount) [count RegEx matches][workaround: use RegExAll and get the array length][see also: StrCount/RegExAll] Prompt: MyLang, one-liner, input vars vText/oRegEx (string/object), output var vCount (int). For haystack vText and RegEx needle oRegEx, return the number of occurrences of oRegEx as vCount. AutoHotkey: ___ [can use: RegExReplace(vText, vNeedle, "", &vCount)] C++: ___ [can use: long vCount = std::distance(std::sregex_iterator(vText.begin(), vText.end(), oRegEx), std::sregex_iterator())] [e.g. auto oRegEx = std::regex(vNeedle)] [requires (sregex_iterator): #include <regex>] C#: ___ Crystal: ___ Excel: ___ Excel VBA: ___ [can use: Set oRegEx = CreateObject("VBScript.RegExp"): oRegEx.Pattern = vNeedle: oRegEx.Global = True: Set oMatches = oRegEx.Execute(vText)] [e.g. vCount = oMatches.Count] Go: ___ Java: ___ JavaScript: ___ [can use (the RegEx must use the global flag): vCount = vText.match(oRegEx)?.length ?? 0] Kotlin: ___ PHP: preg_match_all [e.g. $vCount = preg_match_all($vNeedle, $vText)] Python: ___ R: gregexpr [e.g. oMatch = gregexpr(vNeedle, vText, perl=TRUE)); vCount = ifelse(oMatch[[1]][1]!=-1, length(oMatch[[1]]), 0)] [note (gregexpr): RegEx by default, use 'fixed=TRUE' for a literal string search] [note: uses 'extended' POSIX ERE RegEx if 'perl=TRUE' is omitted] Ruby: ___ Rust: ___ Scala: ___ SQL (MySQL): ___ SQL (PostgreSQL): regexp_count [e.g. regexp_count(MyText, MyNeedle)] SQL (SQLite): ___ Swift: ___ UFL: RegExSplit [or StrSplitRegEx][string to array (split by RegEx needle)][workaround: ChrUnused/RegExReplace/StrSplit][see also: StrSplit] Prompt: MyLang, one-liner, input vars vText/oRegEx (string/object), output var oArray (array). For string vText and needle oRegEx, string to array (split by RegEx needle), discard separators. AutoHotkey: ___ [can use (string split with separator array, array of literal separator strings): oArray := StrSplit(vText, oSep)] C++: ___ [can use: std::sregex_token_iterator] [requires: #include <regex>] C#: Regex.Split [e.g. oArray = Regex.Split(vText, vNeedle)] [WARNING: blank needle: 1 output string per char, with 2 (leading/trailing) blank strings] Crystal: split [e.g. oArray = vText.split(oRegEx)] [note: blank needle: 1 output string per char] Excel: ___ Excel VBA: ___ Go: Split [e.g. oArray := oRegEx.Split(vText, -1)] [note: blank needle: 1 output string per char] Java: split [note: splits based on a RegEx string, not a literal string] [e.g. oArray = vText.split(vNeedle, -1)] [note: blank needle: 1 output string per char] [WARNING: limit param: omitted or 0 to omit trailing blank strings, -1 to maintain them] JavaScript: split [e.g. oArray = vText.split(oRegEx)] [note: blank needle: 1 output string per char] Kotlin: split [e.g. oArray = vText.split(oRegEx).toTypedArray()] [WARNING: blank needle: 1 output string per char, with 2 (leading/trailing) blank strings] PHP: preg_split [e.g. $oArray = preg_split($vNeedle, $vText)] [WARNING: blank needle (blank RegEx: '//'): 1 output string per char, with 2 (leading/trailing) blank strings] Python: re.split [e.g. oList = re.split(oRegEx, vText)] [WARNING: blank needle: 1 output string per char, with 2 (leading/trailing) blank strings] [requires: import re] R: strsplit [note: splits based on RegEx, use fixed=TRUE to split based on a literal string] [e.g. oVec = strsplit(vText, vNeedle)[[1]]] [e.g. oVec = unlist(strsplit(vText, vNeedle))] [note: blank needle: 1 output string per char] [WARNING: omits 1 trailing blank string (if multiple trailing blank strings, only omits the last one)] Ruby: split [e.g. oArray = vText.split(oRegEx, -1)] [note: blank needle: 1 output string per char] [WARNING: limit param: omitted or 0 to omit trailing blank strings, -1 to maintain them] Rust: split [e.g. oVec = oRegEx.split(vText).collect::<Vec<_>>()] [WARNING: blank needle: 1 output string per char, with 2 (leading/trailing) blank strings] [also (limit to n splits): splitn()] Scala: split [note: splits based on a RegEx string, not a literal string] [e.g. oArray = vText.split(vNeedle, -1)] [note: blank needle: 1 output string per char] [WARNING: limit param: omitted or 0 to omit trailing blank strings, -1 to maintain them] SQL (MySQL): ___ SQL (PostgreSQL): regexp_split_to_array [e.g. regexp_split_to_array(MyText, MyNeedle)] SQL (SQLite): ___ Swift: ___ UFL: (RegExSplitKeepDelimDemo) [or RegExSplitKeepSepDemo][note: typically equivalent to RegEx split, but with parentheses around the needle][note: keep any blank strings][e.g. 'abc123def456ghi789jkl000' split by '\d+'] Prompt: MyLang, one-liner, input var vText (string), output var oArray (array). For string vText and needle oRegEx, string to array (split by RegEx needle '\d+'), keep separators. AutoHotkey: ___ C++: ___ [can use: std::sregex_iterator to search for a RegEx needle (the separators), and prefix()/suffix() to get substrings in-between separators)] [requires (sregex_iterator): #include <regex>] C#: oArray = Regex.Split(vText, "(\\d+)") [requires: using System.Text.RegularExpressions] Crystal: oArray = vText.split(/(\d+)/) Excel: ___ Excel VBA: ___ Go: ___ Java: oArray = vText.split("((?<=\\d+)(?!\\d+))|((?<!\\d+)(?=\\d+))", -1) [note: using parentheses doesn't keep delimiters, workaround: use look-ahead and look-behind] JavaScript: oArray = vText.split(/(\d+)/) Kotlin: oArray = Regex("((?<=\\d+)(?!\\d+))|((?<!\\d+)(?=\\d+))").split(vText).toTypedArray() PHP: $oArray = preg_split("/(\\d+)/", $vText, -1, PREG_SPLIT_DELIM_CAPTURE) Python: oRegEx = re.compile("(\\d+)"); oList = re.split(oRegEx, vText) [requires: import re] R: ___ Ruby: oArray = vText.split(/(\d+)/, -1) Rust: ___ Scala: oArray = vText.split("((?<=\\d+)(?!\\d+))|((?<!\\d+)(?=\\d+))", -1) SQL (MySQL): ___ SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: ___ UFL: SubStr [or StrSliceCount/StrSub][return a substring using pos/count][WARNING: languages may use 0-based/1-based string indexes][WARNING: if languages use UTF-8 bytes or UTF-16 shorts, a substring may split within a char] Prompt: MyLang, one-liner, input vars vText/vPos/vCount (string/int/int), output var vTextNew (string). vTextNew is a substring of vText, using start position vPos, and length vCount. AutoHotkey: SubStr [e.g. (UTF-16 shorts, 1-based): vTextNew := SubStr(vText, vPos, vCount)] C++: substr [e.g. (UTF-8 bytes): vTextNew = vText.substr(vPos, vCount)] [WARNING: substr uses bytes, so can frequently split within a char] C#: Substring [e.g. (UTF-16 shorts): vTextNew = vText.Substring(vPos, vCount)] Crystal: ___ [can use (codepoints): vTextNew = vText[vPos...vPos+vCount]] Excel: MID [e.g. (UTF-16 shorts): =MID(A1,MyPos,MyCount)] Excel VBA: Mid [e.g. (UTF-16 shorts): vTextNew = Mid(vText, vPos, vCount)] [note: unlike Excel sheet function, can omit count parameter] Go: ___ [can use (codepoints): vTextNew := string([]rune(vText)[vPos : vPos+vCount])] Java: ___ [can use (UTF-16 shorts): vTextNew = vText.substring(vPos, vPos+vCount)] JavaScript: ___ [can use (UTF-16 shorts): vTextNew = vText.slice(vPos, vPos+vCount)] [deprecated: substr(vPos, vCount)] [note: don't confuse with substring(vPos1, vPos2)] Kotlin: ___ [can use (UTF-16 shorts): vTextNew = vText.slice(vPos..<vPos+vCount)] PHP: mb_substr [e.g. (codepoints): $vTextNew = mb_substr($vText, $vPos, $vCount)] [WARNING: substr uses bytes, so can frequently split within a char] Python: ___ [can use (codepoints): vTextNew = vText[vPos:vPos+vCount]] R: ___ [can use (codepoints, 1-based): vTextNew = substr(vText, vPos, vPos+vCount-1)] [note: substr/substring: equivalent, except substring lets you omit the endpoint] [note: the endpoint is inclusive] Ruby: slice [e.g. vTextNew = vText.slice(vPos, vCount)] [also: vText[vPos...vPos+vCount]] Rust: ___ [can use (codepoints): vTextNew: String = vText.chars().skip(vPos).take(vCount).collect()] Scala: ___ [can use (UTF-16 shorts): vTextNew = vText.substring(vPos, vPos+vCount)] SQL (MySQL): substr [e.g. (codepoints, 1-based): substr(MyText, MyPos, MyCount)] [also: mid] [alias (substring): substr] [WARNING: a value of 0 for pos returns an empty string] [note: if len is negative (or 0), returns a blank string] SQL (PostgreSQL): substr [e.g. (codepoints, 1-based): substr(MyText, MyPos, MyCount)] [also: substring()] [WARNING: non-positive length starts before the string] SQL (SQLite): substr [e.g. (codepoints, 1-based): substr(MyText, MyPos, MyCount)] [alias (substr): substring] [note (a curious feature): a negative count (param Z) returns chars before and excluding pos (param Y)] Swift: ___ [can use (codepoints): vTextNew = String(Array(vText)[vPos..<vPos+vCount])] UFL: StrSliceExc [return a substring using pos1/pos2 (exclusive end)][WARNING: languages may use 0-based/1-based string indexes][note: all approaches below return a string] Prompt: MyLang, one-liner, input vars vText/vPos1/vPos2 (string/int/int), output var vTextNew (string). vTextNew is a substring of vText, using start vPos1, and exclusive end vPos2. AutoHotkey: ___ [can use (1-based): vTextNew := SubStr(vText, vPos1, vPos2-vPos1)] C++: ___ [can use: vTextNew = vText.substr(vPos1, vPos2-vPos1)] C#: ___ [can use: vTextNew = vText.Substring(vPos1, vPos2-vPos1)] Crystal: ___ [can use: vTextNew = vText[vPos1...vPos2]] Excel: ___ [can use: =MID(A1,MyPos1,MyPos2-MyPos1)] Excel VBA: ___ [can use: vTextNew = Mid(vText, vPos1, vPos2 - vPos1)] Go: ___ [can use: vTextNew := string([]rune(vText)[vPos1:vPos2])] Java: substring [e.g. vTextNew = vText.substring(vPos1, vPos2)] [WARNING: pos1/pos2 ('substr'/'substring' is often pos/count)] JavaScript: slice [e.g. vTextNew = vText.slice(vPos1, vPos2)] [also: substring(vPos1, vPos2)] [note: don't confuse with (deprecated) substr(vPos, vCount)] Kotlin: slice [e.g. vTextNew = vText.slice(vPos1..<vPos2)] [also: substring()] [also: subSequence()] PHP: ___ [can use: $vTextNew = mb_substr($vText, $vPos1, $vPos2-$vPos1)] Python: ___ [can use: vTextNew = vText[vPos1:vPos2]] [note: vText[start:end:step]] R: ___ [can use (1-based): vTextNew = substr(vText, vPos1, vPos2-1)] Ruby: slice [e.g. vTextNew = vText.slice(vPos1...vPos2)] [also: vText[vPos1...vPos2]] Rust: ___ [can use: vTextNew: String = vText.chars().skip(vPos1).take(vPos2-vPos1).collect()] [also: vText.get(vPos1..vPos2).unwrap().to_string()] Scala: substring [e.g. vTextNew = vText.substring(vPos1, vPos2)] [WARNING: pos1/pos2 ('substr'/'substring' is often pos/count)] SQL (MySQL): ___ [can use (1-based): substr(MyText, MyPos1, MyPos2-MyPos1)] SQL (PostgreSQL): ___ [can use (1-based): substr(MyText, MyPos1, MyPos2-MyPos1)] SQL (SQLite): ___ [can use (1-based): substr(MyText, MyPos1, MyPos2-MyPos1)] Swift: ___ [can use: vTextNew = String(vText[vText.index(vText.startIndex, offsetBy:vPos1)..<vText.index(vText.startIndex, offsetBy:vPos2)])] [also: vTextNew = String(Array(vText)[vPos1..<vPos2])] [also: vTextNew = String(vText.dropFirst(vPos1).dropLast(vText.count-vPos2))] [also: vTextNew = String(vText.dropFirst(vPos1).prefix(vPos2-vPos1))] UFL: StrSliceInc [return a substring using pos1/pos2 (inclusive end)][WARNING: languages may use 0-based/1-based string indexes][note: all approaches below return a string] Prompt: MyLang, one-liner, input vars vText/vPos1/vPos2 (string/int/int), output var vTextNew (string). vTextNew is a substring of vText, using start vPos1, and inclusive end vPos2. AutoHotkey: ___ [can use (1-based): vTextNew := SubStr(vText, vPos1, vPos2-vPos1+1)] C++: ___ [can use: vTextNew = vText.substr(vPos1, vPos2-vPos1+1)] C#: ___ [can use: vTextNew = vText.Substring(vPos1, vPos2-vPos1+1)] Crystal: ___ [can use: vTextNew = vText[vPos1..vPos2]] Excel: ___ [can use: =MID(A1,MyPos1,MyPos2-MyPos1+1)] Excel VBA: ___ [can use: vTextNew = Mid(vText, vPos1, vPos2 - vPos1 + 1)] Go: ___ [can use: vTextNew := string([]rune(vText)[vPos1 : vPos2+1])] Java: ___ [can use: vTextNew = vText.substring(vPos1, vPos2+1)] [WARNING: pos1/pos2 ('substr'/'substring' is often pos/count)] JavaScript: ___ [can use: vTextNew = vText.slice(vPos1, vPos2+1)] Kotlin: slice [e.g. vTextNew = vText.slice(vPos1..vPos2)] PHP: ___ [can use: $vTextNew = mb_substr($vText, $vPos1, $vPos2-$vPos1+1)] Python: ___ [can use: vTextNew = vText[vPos1:vPos2+1]] R: ___ [can use (1-based): vTextNew = substr(vText, vPos1, vPos2)] Ruby: slice [e.g. vTextNew = vText.slice(vPos1..vPos2)] [also: vText[vPos1..vPos2]] Rust: ___ [can use: vTextNew: String = vText.chars().skip(vPos1).take(vPos2-vPos1+1).collect()] [also: vText.get(vPos1..=vPos2).unwrap().to_string()] Scala: ___ [can use: vTextNew = vText.substring(vPos1, vPos2+1)] [WARNING: pos1/pos2 ('substr'/'substring' is often pos/count)] SQL (MySQL): ___ [can use (1-based): substr(MyText, MyPos1, MyPos2-MyPos1+1)] SQL (PostgreSQL): ___ [can use (1-based): substr(MyText, MyPos1, MyPos2-MyPos1+1)] SQL (SQLite): ___ [can use (1-based): substr(MyText, MyPos1, MyPos2-MyPos1+1)] Swift: ___ [can use: vTextNew = String(Array(vText)[vPos1...vPos2])] [also: vTextNew = String(vText.dropFirst(vPos1).dropLast(vText.count-vPos2-1))] [also: vTextNew = String(vText.dropFirst(vPos1).prefix(vPos2-vPos1+1))] UFL: StrSliceRest [or SubStrRest][get substring from position onwards][note: identical to 'StrDropLeft' for 0-based strings][see also: StrDropLeft] Prompt: MyLang, one-liner, input vars vText/vPos (string/int). vTextNew is a substring of vText, using start vPos, get the rest of the string. AutoHotkey: ___ [can use (1-based): vTextNew := SubStr(vText, vPos)] C++: ___ [can use: vTextNew = vText.substr(vPos)] C#: ___ [can use: vTextNew = vText.Substring(vPos)] Crystal: ___ [can use: vTextNew = vText[vPos..]] Excel: ___ [can use (1-based): =MID(A1,MyPos,LEN(A1))] [e.g. =REPLACE(A1,1,MyPos-1,"")] [e.g. =IFERROR(RIGHT(A1,LEN(A1)-MyPos+1),"")] Excel VBA: ___ [can use (1-based): vTextNew = Mid(vText, vPos)] Go: ___ [can use: vTextNew := string([]rune(vText)[vPos:])] Java: substring [e.g. vTextNew = vText.substring(vPos)] JavaScript: slice [e.g. vTextNew = vText.slice(vPos)] [also: vTextNew = vText.substring(vPos)] [note: don't confuse with (deprecated) substr(vPos)] Kotlin: ___ [can use: vTextNew = vText.drop(vPos)] PHP: ___ [can use: $vTextNew = mb_substr($vText, $vPos)] Python: ___ [can use: vTextNew = vText[vPos:]] R: ___ [can use (1-based): vTextNew = substring(vText, vPos)] Ruby: slice [e.g. vTextNew = vText.slice(vPos..)] [also: vText[vPos..]] Rust: ___ [can use: vTextNew: String = vText.chars().skip(vPos).collect()] [also: vText.get(vPos..).unwrap().to_string()] Scala: substring [e.g. vTextNew = vText.substring(vPos)] SQL (MySQL): ___ [can use (1-based): substr(MyText, MyPos)] SQL (PostgreSQL): ___ [can use (1-based): substr(MyText, MyPos)] SQL (SQLite): ___ [can use (1-based): substr(MyText, MyPos)] Swift: dropFirst [e.g. vTextNew = String(vText.dropFirst(vPos))] [also: vTextNew = String(vText[vText.index(vText.startIndex, offsetBy:vPos)...])] [also: vTextNew = String(Array(vText)[vPos...])] UFL: StrLeft [or StrTakeLeft/StrTakeFirst][get the first n chars][see also: StrFirst] Prompt: MyLang, one-liner, input vars vText/vCount (string/int), output var vTextNew (string). vTextNew is the first vCount chars. AutoHotkey: ___ [can use: vTextNew := SubStr(vText, 1, vCount)] C++: ___ [can use: vTextNew = vText.substr(0, vCount)] C#: ___ [can use: vTextNew = vText.Substring(0, Math.Min(vCount, vText.Length))] Crystal: ___ [can use: vTextNew = vText[...vCount]] Excel: LEFT [e.g. =LEFT(A1,MyCount)] [note: omit Count same as Count 1] Excel VBA: Left [e.g. vTextNew = Left(vText, vCount)] [note: can't omit Count] Go: ___ [can use: vTextNew := string([]rune(vText)[:vCount])] Java: ___ [can use: vTextNew = vText.substring(0, Math.min(vCount, vText.length()))] [WARNING: pos1/pos2 ('substr'/'substring' is often pos/count)] JavaScript: ___ [can use: vTextNew = vText.slice(0, vCount)] [also: substring()] [note: don't confuse with (deprecated) substr(vPos, vCount)] Kotlin: take [e.g. vTextNew = vText.take(vCount)] PHP: ___ [can use: $vTextNew = mb_substr($vText, 0, $vCount)] Python: ___ [can use: vTextNew = vText[:vCount]] R: ___ [can use: vTextNew = substr(vText, 1, vCount)] [also (display width): vTextNew = strtrim(vText, vCount)] Ruby: slice [e.g. vTextNew = vText.slice(0, vCount)] [also: vText.slice(...vCount)] [also: vText[...vCount]] Rust: ___ [can use: vTextNew: String = vText.chars().take(vCount).collect()] Scala: ___ [can use: vTextNew = vText.substring(0, math.min(vCount, vText.length))] [WARNING: pos1/pos2 ('substr'/'substring' is often pos/count)] SQL (MySQL): left [e.g. left(MyText, MyCount)] [also: substr(MyText, 1, MyCount)] SQL (PostgreSQL): left [e.g. left(MyText, MyCount)] [also: substr(MyText, 1, MyCount)] SQL (SQLite): ___ [can use: substr(MyText, 1, MyCount)] Swift: prefix [e.g. vTextNew = String(vText.prefix(vCount))] UFL: StrRight [or StrTakeRight/StrTakeLast][get the last n chars][see also: StrLast] Prompt: MyLang, one-liner, input vars vText/vCount (string/int), output var vTextNew (string). vTextNew is the last vCount chars. AutoHotkey: ___ [can use: vTextNew := SubStr(vText, -vCount)] [note: AHK v1: SubStr(vText, -vCount+1)] [also: vTextNew := SubStr(vText, StrLen(vText)+1-vCount)] C++: ___ [can use: vTextNew = vText.substr(vCount<vText.size()?vText.size()-vCount:0)] [also: vText.substr(std::max<int>(vText.size()-vCount, 0))] [requires (max): #include <algorithm>] C#: ___ [can use: vTextNew = vText.Substring(Math.Max(vText.Length-vCount, 0))] Crystal: ___ [can use: vTextNew = vText[-vCount..]] Excel: RIGHT [e.g. =RIGHT(A1,MyCount)] [note: omit Count same as Count 1] Excel VBA: Right [e.g. vTextNew = Right(vText, vCount)] [note: can't omit Count] Go: ___ [can use: vTextNew := string([]rune(vText)[len([]rune(vText))-vCount:])] Java: ___ [can use: vTextNew = vText.substring(Math.max(vText.length()-vCount, 0))] [WARNING: pos1/pos2 ('substr'/'substring' is often pos/count)] JavaScript: ___ [can use: vTextNew = vText.slice(-vCount)] [also: substring()] Kotlin: takeLast [e.g. vTextNew = vText.takeLast(vCount)] PHP: ___ [can use: $vTextNew = mb_substr($vText, -$vCount)] Python: ___ [can use: vTextNew = vText[-vCount:]] R: ___ [can use: vTextNew = substring(vText, nchar(vText)-vCount+1)] [note: substr/substring: equivalent, except substring lets you omit the endpoint] Ruby: slice [e.g. vTextNew = vText.slice(-vCount..)] [also: vText[-vCount..]] Rust: ___ [can use: vTextNew: String = vText.chars().skip(vText.chars().count()-vCount).collect()] Scala: ___ [can use: vTextNew = vText.substring(math.max(vText.length-vCount, 0))] [WARNING: pos1/pos2 ('substr'/'substring' is often pos/count)] SQL (MySQL): right [e.g. right(MyText, MyCount)] [also: substr(MyText, -MyCount)] [also: substr(MyText, char_length(MyText)-MyCount+1)] SQL (PostgreSQL): right [e.g. right(MyText, MyCount)] [also: substr(MyText, length(MyText)-MyCount+1)] SQL (SQLite): ___ [can use: substr(MyText, -MyCount)] [also: substr(MyText, length(MyText)-MyCount+1)] Swift: suffix [e.g. vTextNew = String(vText.suffix(vCount))] UFL: StrDropLeft [or StrDropFirst][remove the first n chars][note: identical to 'StrSliceRest' for 0-based strings][see also: StrSliceRest/StrUpperFirstOnly] Prompt: MyLang, one-liner, input vars vText/vCount (string/int), output var vTextNew (string). vTextNew is vText with the first vCount chars removed. AutoHotkey: ___ [can use: vTextNew := SubStr(vText, vCount+1)] C++: ___ [can use: vTextNew = vText.substr(vCount)] C#: ___ [can use: vTextNew = vText.Remove(0, vCount)] [also: vTextNew = vText.Substring(vCount)] Crystal: ___ [can use: vTextNew = vText[vCount..]] Excel: ___ [can use: =MID(A1,MyCount+1,LEN(A1))] [e.g. =REPLACE(A1,1,MyCount,"")] [e.g. =IFERROR(RIGHT(A1,LEN(A1)-MyCount),"")] Excel VBA: ___ [can use: vTextNew = Mid(vText, vCount + 1)] Go: ___ [can use: vTextNew := string([]rune(vText)[vCount:])] Java: ___ [can use: vTextNew = vText.substring(vCount)] [also: vTextNew = vText.substring(vCount, vText.length())] JavaScript: ___ [can use: vTextNew = vText.slice(vCount)] [also: vTextNew = vText.substring(vCount)] Kotlin: drop [e.g. vTextNew = vText.drop(vCount)] PHP: ___ [can use: $vTextNew = mb_substr($vText, $vCount)] Python: ___ [can use: vTextNew = vText[vCount:]] R: ___ [can use: vTextNew = substring(vText, vCount+1)] [note: substr/substring: equivalent, except substring lets you omit the endpoint] Ruby: slice [e.g. vTextNew = vText.slice(vCount..)] [also: vText[vCount..]] Rust: ___ [can use: vTextNew: String = vText.chars().skip(vCount).collect()] [also: vText.get(vCount..).unwrap().to_string()] Scala: ___ [can use: vTextNew = vText.substring(vCount)] [also: vTextNew = vText.substring(vCount, vText.length)] SQL (MySQL): ___ [can use: substr(MyText, MyCount+1)] SQL (PostgreSQL): ___ [can use: substr(MyText, MyCount+1)] SQL (SQLite): ___ [can use: substr(MyText, MyCount+1)] Swift: dropFirst [e.g. vTextNew = String(vText.dropFirst(vCount))] [also: vTextNew = String(vText[vText.index(vText.startIndex, offsetBy:vCount)...])] [also: vTextNew = String(Array(vText)[vCount...])] UFL: StrDropRight [or StrDropLast][remove the last n chars] Prompt: MyLang, one-liner, input vars vText/vCount (string/int), output var vTextNew (string). vTextNew is vText with the last vCount chars removed. AutoHotkey: ___ [can use: vTextNew := SubStr(vText, 1, -vCount)] C++: ___ [can use: vTextNew = vText.substr(0, vText.length()-vCount)] C#: ___ [can use: vTextNew = vText.Remove(vText.Length-vCount)] [also: vTextNew = vText.Substring(0, vText.Length-vCount)] Crystal: ___ [can use: vTextNew = vText[...-vCount]] Excel: ___ [can use: drop right 10: =IFERROR(LEFT(A1,LEN(A1)-10),"")] [e.g. drop right 10: =IFERROR(MID(A1,1,LEN(A1)-10),"")] Excel VBA: ___ [can use: vTextNew = Mid(vText, 1, Len(vText) - vCount)] Go: ___ [can use: vTextNew := string([]rune(vText)[:len([]rune(vText))-vCount])] Java: ___ [can use: vTextNew = vText.substring(0, vText.length()-vCount)] JavaScript: ___ [can use: vTextNew = (vCount > 0) ? vText.slice(0, -vCount) : vText] [also: substring()] Kotlin: dropLast [e.g. vTextNew = vText.dropLast(vCount)] PHP: ___ [can use: $vTextNew = mb_substr($vText, 0, -$vCount)] Python: ___ [can use: vTextNew = vText[:-vCount]] R: ___ [can use: vTextNew = substr(vText, 1, nchar(vText)-vCount)] Ruby: slice [e.g. vTextNew = vText.slice(...-vCount)] [also: vText[...-vCount]] Rust: ___ [can use: vTextNew: String = vText.chars().take(vText.chars().count()-vCount).collect()] Scala: ___ [can use: vTextNew = vText.substring(0, vText.length-vCount)] SQL (MySQL): ___ [can use: substr(MyText, 1, char_length(MyText)-MyCount)] SQL (PostgreSQL): ___ [can use: substr(MyText, 1, length(MyText)-MyCount)] SQL (SQLite): ___ [can use: substr(MyText, 1, length(MyText)-MyCount)] Swift: dropLast [e.g. vTextNew = String(vText.dropLast(vCount))] UFL: (StrDropBothEnds) [or StrDropLeftAndRight/StrDropFirstAndLast/StrDropLeftRight/StrDropFirstLast][drop the first n1 chars, and the last n2 chars] Prompt: MyLang, one-liner, input vars vText/vCount1/vCount2 (string/int/int), output var vTextNew (string). vTextNew is vText with the first vCount1 chars dropped, and the last vCount2 chars dropped. AutoHotkey: ___ [can use: vTextNew := SubStr(vText, vCount1+1, -vCount2)] C++: ___ [can use: vTextNew = vText.substr(vCount1, vText.length()-vCount1-vCount2)] C#: ___ [can use: vTextNew = vText.Substring(vCount1, vText.Length-vCount1-vCount2)] Crystal: ___ [can use: vTextNew = vText[vCount1...-vCount2]] Excel: ___ [can use: =MID(A1,MyCount1+1,LEN(A1)-MyCount1-MyCount2)] Excel VBA: ___ [can use: vTextNew = Mid(vText, vCount1 + 1, Len(vText) - vCount1 - vCount2)] Go: ___ [can use: vTextNew := string([]rune(vText)[vCount1 : len([]rune(vText))-vCount2])] Java: ___ [can use: vTextNew = vText.substring(vCount1, vText.length()-vCount2)] JavaScript: ___ [can use: vTextNew = vText.slice(vCount1, vCount2>0 ? -vCount2 : undefined)] Kotlin: ___ [can use: vTextNew = vText.drop(vCount1).dropLast(vCount2)] PHP: ___ [can use: $vTextNew = mb_substr($vText, $vCount1, -$vCount2)] Python: ___ [can use: vTextNew = vText[vCount1:-vCount2]] R: ___ [can use: vTextNew = substr(vText, vCount1+1, nchar(vText)-vCount2)] Ruby: slice [e.g. vTextNew = vText.slice(vCount1...-vCount2)] [also: vText[vCount1...-vCount2]] Rust: ___ [can use: vTextNew: String = vText.chars().skip(vCount1).take(vText.chars().count()-vCount1-vCount2).collect()] Scala: ___ [can use: vTextNew = vText.substring(vCount1, vText.length-vCount2)] SQL (MySQL): ___ [can use: substr(MyText, MyCount1+1, char_length(MyText)-MyCount1-MyCount2)] SQL (PostgreSQL): ___ [can use: substr(MyText, MyCount1+1, length(MyText)-MyCount1-MyCount2)] SQL (SQLite): ___ [can use: substr(MyText, MyCount1+1, length(MyText)-MyCount1-MyCount2)] Swift: ___ [can use: vTextNew = String(vText.dropFirst(vCount1).dropLast(vCount2))] UFL: (StrFirst) [get the first char as a string][see also: StrLeft] Prompt: MyLang, one-liner, input var vText (string), output var vTextNew (string). vTextNew is the first char (Unicode codepoint) of vText as a string. AutoHotkey: ___ [can use (UTF-16 shorts): vTextNew := SubStr(vText, 1, 1)] [also (codepoints): vTextNew := RegExReplace(vText, ".\K.*")] C++: ___ [can use (UTF-8 bytes): vTextNew = vText.substr(0, 1)] [also (UTF-8 bytes): vTextNew = std::string("") + vText[0]] C#: ___ [can use (UTF-16 shorts): vTextNew = vText.Substring(0, 1)] [also (UTF-16 shorts): vTextNew = "" + vText[0]] [also (UTF-16 shorts): vTextNew = "" + vText.First()] [requires (First): using System.Linq] Crystal: ___ [can use (codepoints): vTextNew = vText[0].to_s] [can use (codepoints): vTextNew = vText[0..0]] Excel: LEFT [e.g. (UTF-16 shorts): =LEFT(A1)] [also: =LEFT(A1,1)] Excel VBA: Left [e.g. (UTF-16 shorts): vTextNew = Left(vText, 1)] [note: can't omit Count] Go: ___ [can use (codepoints): vTextNew := string([]rune(vText)[0])] Java: ___ [can use (UTF-16 shorts): vTextNew = "" + vText.charAt(0)] [can use (UTF-16 shorts): vTextNew = vText.substring(0, 1)] [WARNING: pos1/pos2 ('substr'/'substring' is often pos/count)] JavaScript: ___ [can use (codepoints): vTextNew = String.fromCodePoint(vText.codePointAt(0))] [also (codepoints): vTextNew = [...vText][0]] [also (UTF-16 shorts): vTextNew = vText[0]] [also (UTF-16 shorts): vTextNew = vText.charAt()] [also (UTF-16 shorts): vTextNew = vText.slice(0, 1)] [also: substring()] [note: don't confuse with (deprecated) substr(vPos, 1)] Kotlin: take [e.g. (UTF-16 shorts): vTextNew = vText.take(1)] [also (UTF-16 shorts): vTextNew = vText[0].toString()] [also (UTF-16 shorts): vTextNew = vText.first().toString()] PHP: ___ [can use (codepoints): $vTextNew = mb_substr($vText, 0, 1)] [also (UTF-8 bytes): $vTextNew = $vText[0]] Python: ___ [can use (codepoints): vTextNew = vText[0]] R: ___ [can use (codepoints): vTextNew = substr(vText, 1, 1)] [also (codepoints): vTextNew = strsplit(vText, "")[[1]][1]] [also (codepoints): vTextNew = unlist(strsplit(vText, ""))[1]] [note: substring also works] [also (codepoints, display width): vTextNew = strtrim(vText, 1)] Ruby: ___ [can use (codepoints): vTextNew = vText[0]] [also (codepoints): vTextNew = vText.slice(0)] [also (codepoints): vTextNew = vText.slice(0, 1)] [WARNING: slice(0) gets first char, not all chars] [WARNING: slice(index) versus slice(start, length)] Rust: ___ [can use: vTextNew: String = vText.chars().take(1).collect()] [also: vTextNew = format!("{}", vText.chars().next().unwrap())] [also (modifies a string, requires a mutable string, not an &str): vTextNew = vText.remove(0).to_string()] Scala: ___ [can use (UTF-16 shorts): vTextNew = "" + vText.charAt(0)] [can use (UTF-16 shorts): vTextNew = vText.substring(0, 1)] [WARNING: pos1/pos2 ('substr'/'substring' is often pos/count)] SQL (MySQL): ___ [can use: left(MyText, 1)] [also: substr(MyText, 1, 1)] SQL (PostgreSQL): ___ [can use: left(MyText, 1)] [also: substr(MyText, 1, 1)] SQL (SQLite): ___ [can use: substr(MyText, 1, 1)] Swift: first [e.g. (codepoints): vTextNew = String(vText.first!)] [also (codepoints): vTextNew = String(vText.prefix(1))] UFL: (StrLast) [get the last char as a string][see also: StrRight] Prompt: MyLang, one-liner, input var vText (string), output var vTextNew (string). vTextNew is the last char (Unicode codepoint) of vText as a string. AutoHotkey: ___ [can use (UTF-16 shorts): vTextNew := SubStr(vText, -1)] [note: AHK v1: SubStr(vText, 0)] [also (codepoints): vTextNew := RegExReplace(vText, "^(.*)(?=.$)")] C++: ___ [can use (UTF-8 bytes): vTextNew = vText.substr(vText.size()-1)] [also (UTF-8 bytes): vTextNew = std::string("") + vText[vText.size()-1]] C#: ___ [can use (UTF-16 shorts): vTextNew = vText.Substring(vText.Length-1)] [also (UTF-16 shorts): vTextNew = "" + vText[vText.Length-1]] [also (UTF-16 shorts): vTextNew = "" + vText.Last()] [requires (Last): using System.Linq] Crystal: ___ [can use (codepoints): vTextNew = vText[-1].to_s] [also (codepoints): vTextNew = vText[-1..-1]] [also (codepoints): vTextNew = vText[vText.size-1].to_s] Excel: RIGHT [e.g. (UTF-16 shorts): =RIGHT(A1)] [also: =RIGHT(A1,1)] Excel VBA: Right [e.g. (UTF-16 shorts): vTextNew = Right(vText, 1)] [note: can't omit Count] Go: ___ [can use (codepoints): vTextNew := string([]rune(vText)[len([]rune(vText))-1:])] Java: ___ [can use (UTF-16 shorts): vTextNew = "" + vText.charAt(vText.length()-1)] [also: vTextNew = vText.substring(vText.length()-1)] [WARNING: pos1/pos2 ('substr'/'substring' is often pos/count)] JavaScript: ___ [can use (codepoints): vTextNew = [...vText].pop()] [also (UTF-16 shorts): vTextNew = vText.slice(-1)] [also: substring()] [also (UTF-16 shorts): vTextNew = vText.charAt(vText.length-1)] [also (UTF-16 shorts): vTextNew = vText[vText.length-1]] Kotlin: takeLast [e.g. (UTF-16 shorts): vTextNew = vText.takeLast(1)] [also (UTF-16 shorts): vTextNew = vText.last().toString()] [also (UTF-16 shorts): vTextNew = vText[vText.length-1].toString()] PHP: ___ [can use (codepoints): $vTextNew = mb_substr($vText, -1)] [also (UTF-8 bytes): $vTextNew = $vText[-1]] [also (UTF-8 bytes): $vTextNew = $vText[strlen($vText)-1]] Python: ___ [can use (codepoints): vTextNew = vText[-1]] [also (codepoints): vTextNew = vText[len(vText)-1]] R: ___ [can use (codepoints): vTextNew = substring(vText, nchar(vText))] [also (codepoints): vTextNew = substr(vText, nchar(vText), nchar(vText))] [note: substr/substring: equivalent, except substring lets you omit the endpoint] Ruby: ___ [can use (codepoints): vTextNew = vText[-1]] [also (codepoints): vTextNew = vText.slice(-1)] [also (codepoints): vTextNew = vText[vText.length-1]] [WARNING: slice(index) versus slice(start, length)] Rust: ___ [can use (codepoints): vTextNew: String = vText.chars().skip(vText.chars().count()-1).collect()] Scala: ___ [can use (UTF-16 shorts): vTextNew = "" + vText.charAt(vText.length-1)] [also: vTextNew = vText.substring(vText.length-1)] [WARNING: pos1/pos2 ('substr'/'substring' is often pos/count)] SQL (MySQL): ___ [can use: right(MyText, 1)] [also: substr(MyText, -1)] [also: substr(MyText, char_length(MyText))] SQL (PostgreSQL): ___ [can use: right(MyText, 1)] [also: substr(MyText, char_length(MyText))] SQL (SQLite): ___ [can use: substr(MyText, -1)] [also: substr(MyText, length(MyText))] Swift: suffix [e.g. (codepoints): vTextNew = String(vText.last!)] [also (codepoints): vTextNew = String(vText.suffix(1))] UFL: (StrSort) [or StrSorted][sort string based on a delimiter char][see also: Array.Sort] Prompt: MyLang, one-liner, input vars vText/vSep (strings), output var vTextNew (string). For string vText, sort substrings based on 1-char separator vSep. As a comment, if available, show code that would do this, modifying the string directly. AutoHotkey: Sort [e.g. case-sensitive: vTextNew := Sort(vText, "C D" vSep)] [e.g. case-insensitive: vTextNew := Sort(vText, "D" vSep)] [WARNING: case-insensitive by default] C++: ___ C#: ___ [can use: vTextNew = String.Join(vSep, vText.Split(vSep).OrderBy(v=>v, StringComparer.Ordinal))] Crystal: ___ [can use: vTextNew = vText.split(vSep).sort.join(vSep)] Excel: ___ Excel VBA: ___ Go: ___ Java: ___ JavaScript: ___ [can use: vTextNew = vText.split(vSep).sort().join(vSep)] Kotlin: ___ [can use: vTextNew = vText.split(vSep).sorted().joinToString(vSep)] PHP: ___ Python: ___ [can use: vTextNew = vSep.join(sorted(vText.split(vSep)))] R: ___ [can use: vTextNew = paste(sort(unlist(strsplit(vText, vSep, fixed=TRUE))), collapse=vSep)] Ruby: ___ [can use: vTextNew = vText.split(vSep, -1).sort.join(vSep)] [WARNING: limit param: omitted or 0 to omit trailing blank strings, -1 to maintain them] Rust: ___ Scala: ___ [can use: vTextNew = vText.split(java.util.regex.Pattern.quote(vSep), -1).sorted.mkString(vSep)] [WARNING: limit param: omitted or 0 to omit trailing blank strings, -1 to maintain them] SQL (MySQL): ___ SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: ___ [can use: vTextNew = vText.split(separator:vSep, omittingEmptySubsequences:false).sorted().joined(separator:vSep)] UFL: (StrAlphabetize) [or StrAlphabetise/StrSortChars/StrAlphabetized/StrAlphabetised][alphabetise characters in string (case-sensitive)][see also: Array.Sort] Prompt: MyLang, one-liner, input var vText (string), output var vTextNew (string). Alphabetise characters in string (case-sensitive) (sort by Unicode codepoint). As a comment, if available, show code that would do this, modifying the string directly. AutoHotkey: ___ C++: ___ [can use (sorts in-place, ASCII): std::sort(vText.begin(), vText.end())] [WARNING: sorts UTF-8 bytes] C#: ___ [can use: vTextNew = String.Concat(vText.EnumerateRunes().OrderBy(v=>v.Value))] [note: v=>v would also work, but appears to be slower] Crystal: ___ [can use: vTextNew = vText.chars.sort.join] Excel: ___ Excel VBA: ___ Go: ___ [can use: oArray := strings.Split(vText, ""); sort.Sort(sort.StringSlice(oArray)); vTextNew := strings.Join(oArray, "")] Java: ___ [can use: vTextNew = vText.codePoints().boxed().sorted(Integer::compare).collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append).toString()] JavaScript: ___ [can use: vTextNew = [...vText].sort().join("")] Kotlin: ___ [can use: vTextNew = vText.codePoints().sorted().toArray().joinToString(""){String(Character.toChars(it))}] PHP: ___ [can use: $vTextNew = implode("", (static function($v){$o = mb_str_split($v); sort($o); return $o;})($vText))] Python: ___ [e.g. vTextNew = "".join(sorted(vText))] R: ___ [can use: vTextNew = paste(sort(unlist(strsplit(vText, "")), method="radix"), collapse="")] [note (case-sensitive): 'radix' sorts by Unicode codepoint] [WARNING (case-insensitive): omit 'method'] [also: case-sensitive sort and omit 'method', can use e.g. Sys.setlocale("LC_COLLATE", "C")] Ruby: ___ [can use: vTextNew = vText.chars.sort.join] [also (modify in-place): vText.replace(vText.chars.sort.join)] Rust: ___ [can use (sort_by): let mut oVec: Vec<char> = vText.chars().collect(); oVec.sort_by(|v1,v2| v1.cmp(v2)); let vTextNew = oVec.into_iter().collect::<String>()] Scala: ___ [can use: vTextNew = vText.codePoints().mapToObj(v=>new String(Array(v), 0, 1)).sorted().reduce("", _+_)] [e.g. (UTF-16 shorts): vTextNew = vText.sorted] SQL (MySQL): ___ SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: ___ [e.g. vTextNew = String(vText.sorted())] UFL: (StrAlphabetizeCasIns) [or StrAlphabetiseCasIns/StrSortCharsCasIns/StrAlphabetizedCasIns/StrAlphabetisedCasIns][alphabetise characters in string (case-insensitive)][see also: Array.SortCasIns] Prompt: MyLang, one-liner, input var vText (string), output var vTextNew (string). Alphabetise characters in string, case-insensitive (and accent-sensitive) (sort by Unicode codepoint). As a comment, if available, show code that would do this, modifying the string directly. AutoHotkey: ___ C++: ___ [can use (sorts in-place, ASCII): std::sort(vText.begin(), vText.end(), [](char v1, char v2){return std::tolower(static_cast<unsigned char>(v1)) < std::tolower(static_cast<unsigned char>(v2));})] [WARNING: sorts UTF-8 bytes] C#: ___ [can use: vTextNew = String.Concat(vText.EnumerateRunes().OrderBy(v=>Rune.ToUpperInvariant(v).Value))] [also: ToLowerInvariant()] Crystal: ___ [can use: vTextNew = vText.chars.sort_by(&.downcase).join] [also: vTextNew = vText.chars.sort{|v1,v2| v1.downcase <=> v2.downcase}.join] [also: vTextNew = vText.chars.sort{|v1,v2| v1.to_s.compare(v2.to_s, true)}.join] Excel: ___ Excel VBA: ___ Go: ___ Java: ___ [can use: vTextNew = vText.codePoints().boxed().sorted((v1,v2) -> Integer.compare(Character.toLowerCase(v1), Character.toLowerCase(v2))).collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append).toString()] JavaScript: ___ [can use: vTextNew = [...vText].sort((v1,v2)=>v1.localeCompare(v2, undefined, {sensitivity:"accent"})).join("")] Kotlin: ___ [can use: vTextNew = vText.codePoints().mapToObj{Character.toString(it)}.sorted(String.CASE_INSENSITIVE_ORDER).toArray().joinToString("")] PHP: ___ [can use: $vTextNew = implode("", (static function($v){$o = mb_str_split($v); usort($o, static fn($v1,$v2) => strcmp(mb_strtolower($v1), mb_strtolower($v2))); return $o;})($vText))] Python: ___ [can use: vTextNew = "".join(sorted(vText, key=str.lower))] R: ___ [can use: vTextNew = paste(sort(unlist(strsplit(vText, ""))), collapse="")] [WARNING (case-insensitive): omit 'method'] Ruby: ___ [can use: vTextNew = vText.chars.sort_by(&:downcase).join] [also: vTextNew = vText.chars.sort{|v1,v2| v1.downcase <=> v2.downcase}.join] [also (ASCII): vTextNew = vText.chars.sort(&:casecmp).join] [also (modify in-place): vText.replace(vText.chars.sort_by!(&:downcase).join)] Rust: ___ Scala: ___ [can use: vTextNew = vText.codePoints().mapToObj(v=>new String(Array(v), 0, 1)).sorted(java.lang.String.CASE_INSENSITIVE_ORDER).reduce("", _+_)] [can use (UTF-16 shorts): vTextNew = vText.sortBy(_.toLower)] SQL (MySQL): ___ SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: ___ [can use: vTextNew = String(vText.sorted{$0.lowercased()<$1.lowercased()})] UFL: (StrReverse) [or StrReversed][reverse characters in string] Prompt: MyLang, one-liner, input var vText (string), output var vTextNew (string). Reverse characters in string (Unicode codepoints). As a comment, if available, show code that would do this, modifying the string directly. AutoHotkey: ___ C++: std::reverse [e.g. reverses ASCII string in-place: std::reverse(vText.begin(), vText.end())] [WARNING: flips UTF-8 bytes in any non-ASCII chars] [requires: #include <algorithm>] C#: Reverse [e.g. vTextNew = String.Concat(vText.EnumerateRunes().Reverse())] [also: string[] oChars = Regex.Split(vText, "(?s)(?<=.)(?=.)(?![\uDC00-\uDFFF])"); Array.Reverse(oChars); var vTextNew = String.Concat(oChars)] [requires (Regex.Split): using System.Text.RegularExpressions] [note: preserves surrogate pairs] [also: char[] oChars = vText.ToCharArray(); Array.Reverse(oChars); var vTextNew = new string(oChars)] [WARNING (ToCharArray, Reverse): flips UTF-16 shorts in any surrogate pairs] Crystal: reverse [e.g. vTextNew = vText.reverse] [note: preserves surrogate pairs] Excel: ___ Excel VBA: StrReverse [e.g. vTextNew = StrReverse(vText)] [WARNING: flips UTF-16 shorts in any surrogate pairs] Go: ___ [can use: oChars := strings.Split(vText, ""); slices.Reverse(oChars); vTextNew := strings.Join(oChars, "")] [note: preserves surrogate pairs] Java: reverse [e.g. vTextNew = new StringBuilder(vText).reverse().toString()] [note: StringBuilder is faster than StringBuffer] [note: preserves surrogate pairs] JavaScript: ___ [can use: vTextNew = [...vText].reverse().join("")] [note: preserves surrogate pairs] [note: 'Strings are iterated by Unicode code points.'] [also (WARNING: flips UTF-16 shorts in any surrogate pairs): vTextNew = vText.split("").reverse().join("")] Kotlin: reversed [e.g. vTextNew = vText.reversed()] [note: preserves surrogate pairs] PHP: ___ [can use: $vTextNew = implode("", array_reverse(mb_str_split($vText)))] [note: preserves surrogate pairs] [also (WARNING: flips UTF-8 bytes in any non-ASCII chars): $vTextNew = strrev($vText)] Python: ___ [can use: vTextNew = vText[::-1]] [note: preserves surrogate pairs] [note: vText[start:end:step]] R: ___ [can use: vTextNew = paste(rev(unlist(strsplit(vText, ""))), collapse="")] [note: preserves surrogate pairs] Ruby: reverse [e.g. vTextNew = vText.reverse] [also (modify in-place): vText.reverse!] [note: preserves surrogate pairs] Rust: rev [e.g. vTextNew: String = vText.chars().rev().collect()] [note: preserves surrogate pairs] Scala: reverse [e.g. vTextNew = vText.reverse] [also: vTextNew = StringBuilder(vText).reverse.toString] [WARNING (StringBuilder): this does not preserve surrogate pairs (unlike Java)] SQL (MySQL): reverse [e.g. reverse(MyText)] [note: preserves surrogate pairs] SQL (PostgreSQL): reverse [e.g. reverse(MyText)] [note: preserves surrogate pairs] SQL (SQLite): ___ Swift: reversed [e.g. vTextNew = String(vText.reversed())] [note: preserves surrogate pairs] UFL: (StrShuffle) [or StrShuffled][shuffle (randomly sort) characters in string][see also: StrSplitChars/Array.Shuffle/Array.Shuffled/Array.JoinNoSep] Prompt: MyLang, one-liner, input var vText (string), output var vTextNew (string). Shuffle the characters (Unicode codepoints). As a comment, if available, show code that would do this, modifying the string directly. AutoHotkey: ___ [can use (assumes string doesn't contain 'unused'): vUnused := Chr(1), vTextNew := StrReplace(Sort(RegExReplace(vText, ".", "$0" vUnused), "D" vUnused " Random"), vUnused)] C++: std::shuffle [e.g. sorts ASCII string in-place: std::shuffle(vText.begin(), vText.end(), oGen)] [beforehand: std::random_device oRD; std::mt19937 oGen(oRD())] [defunct: std::random_shuffle] [requires (shuffle): #include <algorithm>] C#: ___ [can use: var oRand = new Random(); var vTextNew = String.Concat(vText.EnumerateRunes().OrderBy(_=>oRand.Next()));] [also: var oRand = new Random(); var vTextNew = String.Concat(Regex.Split(vText, "(?s)(?<=.)(?=.)(?![\uDC00-\uDFFF])").OrderBy(_=>oRand.Next()));] [requires (Regex.Split): using System.Text.RegularExpressions] [requires (OrderBy): using System.Linq] Crystal: shuffle [e.g. vTextNew = vText.chars.shuffle.join] Excel: ___ Excel VBA: ___ Go: ___ [can use: oArrayTemp := strings.Split(vText, ""); sort.Slice(oArrayTemp, func(_, _ int) bool { return rand.IntN(2) == 0 }); vTextNew := strings.Join(oArrayTemp, "")] Java: Collections.shuffle [e.g. var oListTemp = vText.codePoints().mapToObj(Character::toString).collect(java.util.stream.Collectors.toList()); java.util.Collections.shuffle(oListTemp); var vTextNew = String.join("", oListTemp);] [also: vTextNew = vText.codePoints().boxed().collect(java.util.stream.Collectors.collectingAndThen(java.util.stream.Collectors.toList(), o->{java.util.Collections.shuffle(o); return o.stream().mapToInt(Integer::intValue).collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append).toString();}))] [also: var oArrayTemp = vText.split("(?s)(?<=.)"); Collections.shuffle(Arrays.asList(oArrayTemp)); var vTextNew = String.join("", oArrayTemp);] [requires (Arrays): import java.util.*] JavaScript: ___ [can use: vTextNew = [...vText].map(v=>[v,Math.random()]).sort((v1,v2) =>v1[1]-v2[1]).map(v=>v[0]).join("")] [also: vTextNew = [...vText].sort(() => Math.random()-0.5).join("")] [also: vTextNew = [...vText].sort((v1,v2)=>(Math.random() < 0.5) ? -1 : 1).join("")] Kotlin: shuffled [e.g. vTextNew = vText.codePoints().mapToObj{Character.toString(it)}.toList().shuffled().joinToString("")] PHP: ___ [can use: $oArrayTemp = mb_str_split($vText); shuffle($oArrayTemp); $vTextNew = implode("", $oArrayTemp);] [WARNING: str_shuffle() shuffles bytes, not codepoints] Python: random.sample [e.g. vTextNew = "".join(random.sample(vText,len(vText)))] [requires: import random] [note: random.shuffle() modifies a list, random.sample() creates a new list] R: ___ [can use: vTextNew = paste(sample(unlist(strsplit(vText, ""))), collapse="")] Ruby: shuffle [e.g. vTextNew = vText.chars.shuffle.join] [also (modify in-place): vText.replace(vText.chars.shuffle!.join)] Rust: ___ [can use: let mut oVecTemp = vText.chars().collect::<Vec<_>>(); oVecTemp.shuffle(&mut rand::rng()); let vTextNew: String = oVecTemp.into_iter().collect();] [requires: use rand::seq::SliceRandom] [defunct: thread_rng() became rng()] Scala: ___ [can use: vTextNew = scala.util.Random.shuffle(vText.codePoints().toArray).map(Character.toString).mkString] [also (UTF-16 shorts): vTextNew = scala.util.Random.shuffle(vText.toList).mkString("")] [also (UTF-16 shorts): vTextNew = scala.util.Random.shuffle(vText.split("")).mkString("")] SQL (MySQL): ___ SQL (PostgreSQL): array_shuffle [e.g. array_to_string(array_shuffle(string_to_array(MyText, NULL)), '')] SQL (SQLite): ___ Swift: shuffled [e.g. vTextNew = String(vText.shuffled())] UFL: (TrimBothLeftRightFuncs) [list the function names for Trim/LTrim/RTrim equivalents, if available][crop chars from both ends/start/end (specify a custom list of chars)] Prompt: MyLang. List the names of the functions (slash-separated) that do trim both, trim left, trim right. Placeholder: '___'. AutoHotkey: Trim/LTrim/RTrim C++: ___/___/___ [can use: strspn/wcsspn to count leading chars] C#: Trim/TrimStart/TrimEnd Crystal: strip/lstrip/rstrip [also (one affix, once): lchop/rchop] [also (trailing line breaks): chomp] Excel: ___/___/___ [MAJOR WARNING: Excel's TRIM() replaces consecutive *interior* spaces with single spaces, in addition to trimming leading/trailing whitespace] [note: TRIM doesn't handle custom lists] Excel VBA: Trim/LTrim/RTrim [note: Excel VBA's Trim() does not modify interior spaces] [note: Trim/LTrim/RTrim don't handle custom lists] Go: strings.Trim/strings.TrimLeft/strings.TrimRight Java: strip/stripLeading/stripTrailing [also (removes ASCII chars only): trim] [note: trim/strip/stripLeading/stripTrailing don't handle custom lists] JavaScript: trim/trimStart/trimEnd [note: trim/trimStart/trimEnd don't handle custom lists] Kotlin: trim/trimStart/trimEnd PHP: mb_trim/mb_ltrim/mb_rtrim [also (remove ASCII chars only): trim/ltrim/rtrim] [alias (rtrim): chop] [WARNING: use: '..' to specify a char range] Python: str.strip/str.lstrip/str.rstrip [also (remove any common leading whitespace from lines): textwrap.dedent] R: trimws/trimws/trimws [WARNING: the 'whitespace' param uses RegEx] Ruby: strip/lstrip/rstrip [also: chop/chomp/delete_prefix/delete_suffix] [note: strip/lstrip/rstrip don't handle custom lists] Rust: trim_matches/trim_start_matches/trim_end_matches [also (don't handle custom lists): trim/trim_start/trim_end] [deprecated: vText.trim_left(), vText.trim_right()] Scala: strip/stripLeading/stripTrailing [also (removes ASCII chars only): trim] [note: trim/strip/stripLeading/stripTrailing don't handle custom lists] SQL (MySQL): trim/ltrim/rtrim [note: trim/ltrim/rtrim don't handle custom lists] [WARNING: trims one single/multi-char string, not multiple individual chars: TRIM with 'BOTH'/'LEADING'/'TRAILING'/no (i.e. 'BOTH') keyword: e.g. trim(BOTH MyNeedleString FROM MyText)] SQL (PostgreSQL): btrim/ltrim/rtrim [also: trim(BOTH FROM MyText, MyNeedleChars)] [note: can replace 'BOTH' with 'LEADING'/'TRAILING'] SQL (SQLite): trim/ltrim/rtrim Swift: ___/___/___ [note: trimmingCharacters doesn't handle custom lists] UFL: Trim [or StrTrim/TrimBoth/StrTrimBoth][crop chars from both ends (specify a custom list of chars)][see also: RegExReplace/TrimCustomDemo] Prompt: MyLang, one-liner, input vars vText/vNeedleChars (strings), output var vTextNew (string). Trim both ends of vText, crop by the chars (Unicode codepoints) in vNeedleChars. AutoHotkey: Trim [e.g. vTextNew := Trim(vText, vNeedleChars)] C++: ___ C#: Trim [e.g. vTextNew = vText.Trim(vNeedleChars.ToCharArray())] [also: e.g. char[] oNeedleChars = ['a','b','c']; var vText = "abcdefghi".Trim(oNeedleChars);] Crystal: strip [e.g. vTextNew = vText.strip(vNeedleChars)] Excel: ___ Excel VBA: ___ Go: strings.Trim [e.g. vTextNew := strings.Trim(vText, vNeedleChars)] Java: ___ JavaScript: ___ Kotlin: trim [e.g. vTextNew = vText.trim(*vNeedleChars.toCharArray())] [also: e.g. var oNeedleChars = charArrayOf('a','b','c'); var vTextNew = vText.trim(*oNeedleChars)] [also: vTextNew = vText.trim{it in vNeedleChars}] PHP: mb_trim [e.g. $vTextNew = mb_trim($vText, $vNeedleChars)] Python: str.strip [e.g. vTextNew = vText.strip(vNeedleChars)] [also: vTextNew = str.strip(vText, vNeedleChars)] R: trimws [e.g. vTextNew = trimws(vText, "both", vNeedleCharsRx)] [also: vTextNew = trimws(vText, whitespace=vNeedleCharsRx)] [WARNING: the 'whitespace' param uses RegEx] Ruby: ___ Rust: trim_matches [e.g. vTextNew = vText.trim_matches(|c|vNeedleChars.contains(c))] [also: vTextNew = vText.trim_matches(&vNeedleChars.chars().collect::<Vec<char>>()[..])] [also: e.g. let oNeedleChars = vec!['a','b','c']; let vText = "abcdefghi".trim_matches(&oNeedleChars[..]);] Scala: ___ SQL (MySQL): ___ SQL (PostgreSQL): btrim [e.g. btrim(MyText, MyNeedleChars)] [also: trim(BOTH FROM MyText, MyNeedleChars)] [also: trim(BOTH MyNeedleChars FROM MyText)] SQL (SQLite): trim [e.g. trim(MyText, MyNeedleChars)] Swift: ___ [can use: vTextNew = vText.trimmingCharacters(in:CharacterSet(charactersIn:vNeedleChars))] [requires (CharacterSet): import Foundation] UFL: LTrim [or StrLTrim][crop chars from start (specify a custom list of chars)][see also: RegExReplace/TrimPrefix/TrimIndent] Prompt: MyLang, one-liner, input vars vText/vNeedleChars (strings), output var vTextNew (string). Left trim vText, crop by the chars (Unicode codepoints) in vNeedleChars. AutoHotkey: LTrim [e.g. vTextNew := LTrim(vText, vNeedleChars)] C++: ___ C#: TrimStart [e.g. vTextNew = vText.TrimStart(vNeedleChars.ToCharArray())] Crystal: lstrip [e.g. vTextNew = vText.lstrip(vNeedleChars)] Excel: ___ Excel VBA: ___ Go: strings.TrimLeft [e.g. vTextNew := strings.TrimLeft(vText, vNeedleChars)] Java: ___ JavaScript: ___ Kotlin: trimStart [e.g. vTextNew = vText.trimStart(*vNeedleChars.toCharArray())] PHP: mb_ltrim [e.g. $vTextNew = mb_ltrim($vText, $vNeedleChars)] Python: str.lstrip [e.g. vTextNew = vText.lstrip(vNeedleChars)] R: trimws [e.g. vTextNew = trimws(vText, "left", vNeedleCharsRx)] [WARNING: the 'whitespace' param uses RegEx] Ruby: ___ Rust: trim_start_matches [e.g. vTextNew = vText.trim_start_matches(|c|vNeedleChars.contains(c))] Scala: ___ SQL (MySQL): ___ SQL (PostgreSQL): ltrim [e.g. ltrim(MyText, MyNeedleChars)] [also: trim(LEADING FROM MyText, MyNeedleChars)] [also: trim(LEADING MyNeedleChars FROM MyText)] SQL (SQLite): ltrim [e.g. ltrim(MyText, MyNeedleChars)] Swift: ___ [can use: vTextNew = String(vText.drop{vNeedleChars.contains($0)})] UFL: RTrim [or StrRTrim][crop chars from end (specify a custom list of chars)][see also: RegExReplace/TrimSuffix] Prompt: MyLang, one-liner, input vars vText/vNeedleChars (strings), output var vTextNew (string). Right trim vText, crop by the chars (Unicode codepoints) in vNeedleChars. AutoHotkey: RTrim [e.g. vTextNew := RTrim(vText, vNeedleChars)] C++: ___ C#: TrimEnd [e.g. vTextNew = vText.TrimEnd(vNeedleChars.ToCharArray())] Crystal: rstrip [e.g. vTextNew = vText.rstrip(vNeedleChars)] Excel: ___ Excel VBA: ___ Go: strings.TrimRight [e.g. vTextNew := strings.TrimRight(vText, vNeedleChars)] Java: ___ JavaScript: ___ Kotlin: trimEnd [e.g. vTextNew = vText.trimEnd(*vNeedleChars.toCharArray())] PHP: mb_rtrim [e.g. $vTextNew = mb_rtrim($vText, $vNeedleChars)] Python: str.rstrip [e.g. vTextNew = vText.rstrip(vNeedleChars)] R: trimws [e.g. vTextNew = trimws(vText, "right", vNeedleCharsRx)] [WARNING: the 'whitespace' param uses RegEx] Ruby: ___ Rust: trim_end_matches [e.g. vTextNew = vText.trim_end_matches(|c|vNeedleChars.contains(c))] Scala: ___ SQL (MySQL): ___ SQL (PostgreSQL): rtrim [e.g. rtrim(MyText, MyNeedleChars)] [also: trim(TRAILING FROM MyText, MyNeedleChars)] [also: trim(TRAILING MyNeedleChars FROM MyText)] SQL (SQLite): rtrim [e.g. rtrim(MyText, MyNeedleChars)] Swift: ___ [can use: vTextNew = String(vText.reversed().drop{vNeedleChars.contains($0)}.reversed())] UFL: (TrimCustomDemo) [crop chars from start and end (specify a custom list of chars)] Prompt: MyLang, one-liner, output var vTextNew (string). Trim both ends of the string "abcdefghi", by the chars (Unicode codepoints) in the string "abcghi". AutoHotkey: vText := Trim("abcdefghi", "abcghi") C++: ___ C#: vText = "abcdefghi".Trim("abcghi".ToCharArray()) [also: vText = "abcdefghi".Trim(['a','b','c','g','h','i'])] Crystal: vText = "abcdefghi".strip("abcghi") Excel: ___ Excel VBA: ___ Go: vText := strings.Trim("abcdefghi", "abcghi") Java: ___ JavaScript: ___ Kotlin: vText = "abcdefghi".trim(*"abcghi".toCharArray()) [also: vText = "abcdefghi".trim('a','b','c','g','h','i')] [also: vText = "abcdefghi".trim(*charArrayOf('a','b','c','g','h','i'))] PHP: $vText = mb_trim("abcdefghi", "abcghi") Python: vText = "abcdefghi".strip("abcghi") [also: vText = str.strip("abcdefghi", "abcghi")] R: vText = trimws("abcdefghi", "both", "[abcghi]") [also: vText = trimws("abcdefghi", whitespace="[abcghi]")] Ruby: ___ Rust: vText = "abcdefghi".trim_matches(['a','b','c','g','h','i']) [also: vText = "abcdefghi".trim_matches(|c|"abcghi".contains(c))] [also: vText = "abcdefghi".trim_matches(&"abcghi".chars().collect::<Vec<char>>()[..])] Scala: ___ SQL (MySQL): ___ SQL (PostgreSQL): btrim('abcdefghi', 'abcghi') SQL (SQLite): trim('abcdefghi', 'abcghi') Swift: ___ [can use: vText = "abcdefghi".trimmingCharacters(in:CharacterSet(charactersIn:"abcghi"))] [requires (CharacterSet): import Foundation] UFL: (TrimPrefix) [or StrTrimPrefix][if string starts with prefix, return string with prefix removed (exactly once), else return string unchanged][see also: LTrim/TrimIndent/SymPfxHex] Prompt: MyLang, one-liner, input vars vText/vPfx (strings), output var vTextNew (string). If string starts with prefix (vPfx), return string with prefix removed (exactly once), else return string unchanged. AutoHotkey: ___ C++: ___ C#: ___ Crystal: lchop [e.g. vTextNew = vText.lchop(vPfx)] Excel: ___ Excel VBA: ___ Go: strings.TrimPrefix [e.g. vTextNew := strings.TrimPrefix(vText, vPfx)] Java: ___ JavaScript: ___ Kotlin: removePrefix [e.g. vTextNew = vText.removePrefix(vPfx)] PHP: ___ Python: removeprefix [e.g. vTextNew = vText.removeprefix(vPfx)] R: ___ Ruby: delete_prefix [e.g. vTextNew = vText.delete_prefix(vPfx)] Rust: strip_prefix [e.g. vTextNew = vText.strip_prefix(vPfx).unwrap_or(vText)] Scala: stripPrefix [e.g. vTextNew = vText.stripPrefix(vPfx)] SQL (MySQL): ___ SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: ___ UFL: (TrimSuffix) [or StrTrimSuffix][if string ends with suffix, return string with suffix removed (exactly once), else return string unchanged][see also: RTrim] Prompt: MyLang, one-liner, input vars vText/vSfx (strings), output var vTextNew (string). If string ends with suffix (vSfx), return string with suffix removed (exactly once), else return string unchanged. AutoHotkey: ___ C++: ___ C#: ___ Crystal: rchop [e.g. vTextNew = vText.rchop(vSfx)] Excel: ___ Excel VBA: ___ Go: strings.TrimSuffix [e.g. vTextNew := strings.TrimSuffix(vText, vSfx)] Java: ___ JavaScript: ___ Kotlin: removeSuffix [e.g. vTextNew = vText.removeSuffix(vSfx)] PHP: ___ Python: removesuffix [e.g. vTextNew = vText.removesuffix(vSfx)] R: ___ Ruby: delete_suffix [e.g. vTextNew = vText.delete_suffix(vSfx)] Rust: strip_suffix [e.g. vTextNew = vText.strip_suffix(vSfx).unwrap_or(vText)] Scala: stripSuffix [e.g. vTextNew = vText.stripSuffix(vSfx)] SQL (MySQL): ___ SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: ___ UFL: (TrimIndent) [or StrTrimIndent/StrDedent][find the longest common prefix of whitespace (find the least-indented line), across lines, and remove that amount of whitespace][see also: LTrim/TrimPrefix/StrMultiLineDemo] Prompt: MyLang, one-liner, input var vText (string), output var vTextNew (string). Find the longest common prefix of whitespace (find the least-indented line), across lines, and remove that amount of whitespace. As a comment, state whether multi-line string syntax does this natively. AutoHotkey: ___ [WARNING (multi-line strings): continuation sections: trims indent based on first line] [note: continuation sections: prevent trim via 'LTrim0' option] C++: ___ C#: ___ [note (multi-line strings): trims indent based on position of closing """] Crystal: ___ [note (multi-line strings): trims indent based on position of closing tag for <<-MYTEXT] Excel: ___ Excel VBA: ___ Go: ___ Java: ___ [note (multi-line strings): trims indent based on position of closing """] JavaScript: ___ Kotlin: trimIndent [e.g. vTextNew = vText.trimIndent()] [also: trimMargin(): trim at first pipe (or custom char)] PHP: ___ [note (multi-line strings): trims indent based on position of closing Nowdoc (e.g. <<<'EOT') or Heredoc (e.g. <<<EOT)] Python: textwrap.dedent [e.g. vTextNew = textwrap.dedent(vText)] [requires: import textwrap] R: ___ Ruby: ___ [note (multi-line strings): trims based on the opening tag: <<~MYTEXT (trims indents), <<-MYTEXT (preserves indents)] Rust: ___ Scala: ___ [note: stripMargin(): trim at first pipe (or custom char)] SQL (MySQL): ___ SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: ___ [note (multi-line strings): trims indent based on position of closing """] UFL: StrDiffFirst [or StrFirstDiff/StrLongestCommonPrefixLen][find position of first(/nth) difference][get length of longest common prefix][WARNING: languages may use 0-based/1-based string indexes][note: StrDiff (find the nth/nth-to-last difference)] Prompt: MyLang, one-liner, input vars vText1/vText2 (strings). Get the length of the longest common prefix. AutoHotkey: ___ C++: ___ [can use: std::mismatch] [note: memcmp/strcmp/wcscmp indicates which is greater] C#: ___ [can use: Zip/TakeWhile/Count] Crystal: ___ Excel: ___ Excel VBA: ___ Go: ___ Java: ___ [can use: StringUtils.difference] JavaScript: ___ Kotlin: commonPrefixWith PHP: ___ [note: can apply xor to strings e.g. strspn($vText1 ^ $vText2, "\0")] Python: ___ R: ___ [can use: which(oVec1 != oVec2)[1]] [note: use strsplit() to turn strings into vectors] Ruby: ___ Rust: ___ Scala: ___ [can use: StringUtils.difference] SQL (MySQL): ___ SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: commonPrefix UFL: StrDiffLast [or StrLastDiff/StrLongestCommonSuffixLen][find position of last(/nth-to-last) difference][get length of longest common suffix][WARNING: languages may use 0-based/1-based string indexes] Prompt: MyLang, one-liner, input vars vText1/vText2 (strings). Get the length of the longest common suffix. AutoHotkey: ___ C++: ___ [can use: std::mismatch] C#: ___ Crystal: ___ Excel: ___ Excel VBA: ___ Go: ___ Java: ___ JavaScript: ___ Kotlin: commonSuffixWith PHP: ___ [note: can apply xor to strings e.g. strspn($vText1 ^ $vText2, "\0")] Python: ___ R: ___ [can use: tail(which(oVec1 != oVec2), 1)] [note: use strsplit to turn strings into vectors] Ruby: ___ Rust: ___ Scala: ___ SQL (MySQL): ___ SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: ___ UFL: StrConcat [or StrPrepended/StrAppended][creates a new string][see also: StrJoin/Array.Join/Format/StrPrepend/StrAppend/OpConcat] Prompt: MyLang, one-liner, input vars vText1/vText2/vText3 (strings), output var vTextNew (string). Concatenate strings vText1/vText2/vText3. AutoHotkey: ___ [can use (auto-concat): e.g. vTextNew := vText1 vText2 vText3] [can use (.): e.g. vTextNew := vText1 . vText2 . vText3] [also: vTextNew := Format("{}{}{}", vText1, vText2, vText3)] C++: ___ [can use: +] [WARNING: append() modifies the string] [also: strcat/wcscat] C#: Concat [e.g. vTextNew = String.Concat(vText1, vText2, vText3)] [can use: +] Crystal: ___ [can use: +] Excel: CONCAT [can use: &] [e.g. =A1&B1&C1] [deprecated: CONCATENATE()] [e.g. =CONCATENATE(A1,B1,C1)] [version: Excel 2016: CONCAT() replaces CONCATENATE()] Excel VBA: ___ [also: &] [also: +] Go: ___ [can use: +] Java: concat [e.g. vTextNew = vText1.concat(vText2).concat(vText3)] [can use: +] [also: String.join("", vText1, vText2, vText3)] JavaScript: concat [e.g. vTextNew = vText1.concat(vText2, vText3)] [can use: +] Kotlin: plus [e.g. vTextNew = vText1.plus(vText2).plus(vText3)] [can use: +] [WARNING: may fail as an unresolved reference: vText1.concat(vText2)] PHP: ___ [can use: .] [e.g. $vTextNew = $vText1 . $vText2 . $vText3] Python: operator.concat [e.g. vTextNew = operator.concat(operator.concat(vText1, vText2), vText3)] [can use: +] [can use: "".join([vText1, vText2, vText3])] [requires: import operator] R: ___ [can use: paste0(vText1, vText2, vText3)] [also: paste(vText1, vText2, vText3, sep="")] Ruby: ___ [can use: +] [WARNING: concat() modifies the string] Rust: ___ [can use: format!("{}{}{}", vText1, vText2, vText3)] [also: vText1 + &vText2 + &vText3] [also: vText1.to_owned() + vText2 + vText3] [also: vText1.clone() + &vText2 + &vText3] [WARNING: concat!() only accepts string literals, not variables] Scala: concat [e.g. vTextNew = vText1.concat(vText2).concat(vText3)] [can use: +] [also: String.join("", vText1, vText2, vText3)] SQL (MySQL): concat [e.g. concat(MyText1, MyText2, MyText3)] [can use: ||] [requires (||): set sql_mode=PIPES_AS_CONCAT] SQL (PostgreSQL): concat [e.g. concat(MyText1, MyText2, MyText3)] [can use: ||] [also: format('%s%s%s', MyText1, MyText2, MyText3)] [also: array_to_string(ARRAY[MyText1, MyText2, MyText3], '')] [MAJOR WARNING: PostgreSQL has a 100-param limit (max_function_args), use array_to_string() or repeated || as a workaround] SQL (SQLite): concat [e.g. concat(MyText1, MyText2, MyText3)] [can use: ||] [MAJOR WARNING: SQLite had an 'about 100'-param limit (e.g. 127) (SQLITE_MAX_FUNCTION_ARG) until v3.48.0, use repeated || as a workaround] Swift: ___ [can use: +] UFL: (StrIntConcat) [or StrConcatInt][can concatenate string and int directly?][concatenate strings/ints][see also: PrintKeyValueConcat/PrintKeyValueAsPair/PrintMultDemo/OpConcat/SymCharPlusStrIntDemo/MakeFuncForEachWithIndexDemoPrintIntStr/MakeFuncReduceDemoConcatStrInt] Prompt: MyLang, two one-liners, input vars vText/vNum (string/int). Show the simplest approach to concatenate a string and an int, and an int and a string. Show 2 code examples, comma-space-separated, with no return values, e.g. 'vText + vNum, vNum + vText'. AutoHotkey: yes [e.g. vText vNum] [e.g. vNum vText] [also: vText . vNum] [also: vNum . vText] C++: no [can use: vText + std::to_string(vNum)] [can use: std::to_string(vNum) + vText] C#: yes [e.g. vText + vNum] [e.g. vNum + vText] Crystal: no [can use: vText + vNum.to_s] [also: vNum.to_s + vText] Excel: yes [e.g. =A1&B1] [e.g. =B1&A1] Excel VBA: yes [e.g. vText & vNum] [e.g. vNum & vText] Go: no [can use: vText + strconv.Itoa(vNum)] [also: strconv.Itoa(vNum) + vText] [also: fmt.Sprintf("%v%v", vText, vNum)] [requires (Itoa): import "strconv"] Java: yes [e.g. vText + vNum] [e.g. vNum + vText] JavaScript: yes [e.g. vText + vNum] [e.g. vNum + vText] Kotlin: depends on order [e.g. vText + vNum] [can use: "" + vNum + vText] PHP: yes [e.g. $vText . $vNum] [e.g. $vNum . $vText] Python: no [can use: vText + str(vNum)] [also: str(vNum) + vText] R: yes [e.g. paste0(vText, vNum)] [e.g. paste0(vNum, vText)] Ruby: no [can use: vText + vNum.to_s] [also: vNum.to_s + vText] Rust: no [can use: format!("{}{}", vText, vNum)] [can use: format!("{}{}", vNum, vText)] Scala: yes [e.g. vText + vNum] [e.g. s"$vNum$vText"] [e.g. s"${vNum}${vText}"] [deprecated: vNum + vText] SQL (MySQL): yes [e.g. MyText || MyNum] [e.g. MyNum || MyText] [also: concat()] [requires (||): set sql_mode=PIPES_AS_CONCAT] SQL (PostgreSQL): yes [e.g. MyText || MyNum] [e.g. MyNum || MyText] SQL (SQLite): yes [e.g. MyText || MyNum] [e.g. MyNum || MyText] Swift: no [can use: vText + String(vNum)] [can use: String(vNum) + vText] UFL: StrPadLeft [e.g. pad 'abc' with 3 chars (padding on the left)][WARNING: pad left = justify right][see also: StrRept/StrPadZero/Format] Prompt: MyLang, one-liner. Pad 'abc' with underscores to make it 6 chars long (padding on the left). AutoHotkey: ___ [e.g. spaces: Format("{:6}", "abc")] [e.g. zeros: Format("{:06}", "abc")] C++: std::format [e.g. std::format("{:_>6s}", "abc")] [also: sprintf/vsprintf] C#: PadLeft [e.g. "abc".PadLeft(6, '_')] Crystal: rjust [e.g. "abc".rjust(6, '_')] Excel: ___ [e.g. zeros: =TEXT(123,"000000")] [e.g. zeros: =TEXT(123,REPT("0",6))] [note: fails on non-numbers] Excel VBA: ___ [e.g. zeros: Format(123, "000000")] [e.g. zeros: Format(123, WorksheetFunction.Rept("0", 6))] [note: fails on non-numbers] [also: WorksheetFunction.Text(123, vFormat)] Go: ___ [e.g. spaces: fmt.Sprintf("%6s", "abc")] Java: ___ [e.g. String.format("%1$6s", "abc")] JavaScript: padStart [e.g. "abc".padStart(6, "_")] Kotlin: padStart [e.g. "abc".padStart(6, '_')] PHP: mb_str_pad [e.g. mb_str_pad("abc", 6, "_", STR_PAD_LEFT)] [also (bytes): str_pad] Python: str.rjust [e.g. "abc".rjust(6, "_")] [note: str.zfill() pads leading zeros, e.g. "abc".zfill(6)] R: ___ [e.g. spaces: format("abc", justify="l", width=6)] Ruby: rjust [e.g. "abc".rjust(6, "_")] Rust: format [e.g. format!("{:_>6}", "abc")] Scala: ___ [e.g. String.format("%1$6s", "abc")] SQL (MySQL): lpad [e.g. lpad('abc', 6, '_')] [MAJOR WARNING: lpad() can crop strings] SQL (PostgreSQL): lpad [e.g. lpad('abc', 6, '_')] [also: spaces: format('%6s', 'abc')] [MAJOR WARNING: lpad() can crop strings] SQL (SQLite): ___ [e.g. spaces: format('%6s', 'abc')] [deprecated: printf (an alias of format)] Swift: ___ [e.g. String(String("abc".reversed()).padding(toLength:6, withPad:"_", startingAt:0).reversed())] [MAJOR WARNING: padding() can crop strings] [note: padding only pads left, reverse text twice as a workaround] [also: stringByPaddingToLength()] [requires (padding): import Foundation] UFL: StrPadRight [e.g. pad 'abc' with 3 chars (padding on the right)][WARNING: pad right = justify left][see also: StrRept] Prompt: MyLang, one-liner. Pad 'abc' with underscores to make it 6 chars long (padding on the right). AutoHotkey: ___ [e.g. spaces: Format("{:-6}", "abc")] C++: std::format [e.g. std::format("{:_<6s}", "abc")] C#: PadRight [e.g. "abc".PadRight(6, '_')] Crystal: ljust [e.g. "abc".ljust(6, '_')] Excel: ___ Excel VBA: ___ Go: ___ [e.g. spaces: fmt.Sprintf("%-6s", "abc")] Java: ___ [e.g. String.format("%1$-6s", "abc")] JavaScript: padEnd [e.g. "abc".padEnd(6, "_")] Kotlin: padEnd [e.g. "abc".padEnd(6, '_')] PHP: mb_str_pad [e.g. mb_str_pad("abc", 6, "_", STR_PAD_RIGHT)] [note: STR_PAD_RIGHT can be omitted, but adds clarity] [also (bytes): str_pad] Python: str.ljust [e.g. "abc".ljust(6, "_")] R: ___ [e.g. spaces: format("abc", justify="r", width=6)] [note: justify="r" can be omitted, but adds clarity] Ruby: ljust [e.g. "abc".ljust(6, "_")] Rust: format [e.g. format!("{:_<6}", "abc")] Scala: ___ [e.g. String.format("%1$-6s", "abc")] SQL (MySQL): rpad [e.g. rpad('abc', 6, '_')] [MAJOR WARNING: rpad() can crop strings] SQL (PostgreSQL): rpad [e.g. rpad('abc', 6, '_')] [also: spaces: format('%-6s', 'abc')] [MAJOR WARNING: rpad() can crop strings] SQL (SQLite): ___ [e.g. spaces: format('%-6s', 'abc')] [deprecated: printf (an alias of format)] Swift: padding [e.g. "abc".padding(toLength:6, withPad:"_", startingAt:0)] [MAJOR WARNING: padding() can crop strings] [also: stringByPaddingToLength()] [requires (padding): import Foundation] UFL: (StrPadBoth) [or StrPadBothSides][e.g. pad 'abc' with 3 chars either side][justify centre, align centre][see also: StrRept] Prompt: MyLang, one-liner. Pad 'abc' with underscores to make it 9 chars long (padding on both sides). AutoHotkey: ___ C++: std::format [e.g. std::format("{:_^9s}", "abc")] C#: ___ Crystal: center [e.g. "abc".center(9, '_')] Excel: ___ Excel VBA: ___ Go: ___ Java: ___ JavaScript: ___ [can use: vTextNew = "abc".padStart(6, "_").padEnd(9, "_")] Kotlin: ___ PHP: mb_str_pad [e.g. mb_str_pad("abc", 9, "_", STR_PAD_BOTH)] [also (bytes): str_pad] Python: format [e.g. "{:_^9}".format("abc")] R: ___ [e.g. spaces: format("abc", justify="c", width=9)] Ruby: center [e.g. "abc".center(9, "_")] Rust: format [e.g. format!("{:_^9}", "abc")] Scala: ___ SQL (MySQL): ___ SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: ___ UFL: StrSpan [span][how many of the initial chars are in the needle list][see also: RegExIndex/LTrim] Prompt: MyLang, one-liner, input vars vText/vNeedleChars (strings). Span: state how many of the initial chars of string vText are in the char list string vNeedleChars. AutoHotkey: ___ [can use (UTF-16 shorts): StrLen(vText) - StrLen(LTrim(vText, vNeedleChars))] C++: std::strspn [e.g. (UTF-8 bytes): std::strspn(vText.c_str(), vNeedleChars.c_str())] [note: 'Returns the length of the maximum initial segment (span) of [dest], that consists of only the characters [found (strspn)/not found (strcspn)] in [src].'] [also: wcsspn] C#: ___ [can use (UTF-16 shorts): vText.Length - vText.TrimStart(oNeedleChars).Length] Crystal: ___ [can use (codepoints): vText.size - vText.lstrip(vNeedleChars).size] [also: scan()] Excel: ___ Excel VBA: ___ Go: ___ [can use (UTF-8 bytes): len(vText) - len(strings.TrimLeft(vText, vNeedleChars))] Java: ___ JavaScript: ___ Kotlin: ___ [can use (UTF-16 shorts): vText.length - vText.trimStart(*vNeedleChars.toCharArray()).length] PHP: strspn [e.g. (UTF-8 bytes): strspn($vText, $vNeedleChars)] Python: ___ [can use (codepoints): len(vText) - len(vText.lstrip(vNeedleChars))] R: ___ Ruby: ___ [can use: scan()] Rust: ___ [can use (UTF-8 bytes): vText.len() - vText.trim_start_matches(oNeedleChars).len()] Scala: ___ SQL (MySQL): ___ SQL (PostgreSQL): ___ [can use (codepoints): length(MyText) - length(ltrim(MyText, MyNeedleChars))] SQL (SQLite): ___ [can use (codepoints): length(MyText) - length(ltrim(MyText, MyNeedleChars))] Swift: ___ UFL: StrCompSpan [how many of the initial chars are *not* in the needle list][complementary span][how many chars before we see a char that is in the needle list][count leading chars (of haystack that appear) in (needle) list (e.g. count the leading whitespace chars, e.g. count how many chars would be removed by a left trim)][count leading chars not in list (e.g. create temp string: create a copy of haystack with needle chars removed, count how many chars in original haystack would be removed by a left trim, removing chars in temp string)][see also: RegExIndex/LTrim] Prompt: MyLang, one-liner, input vars vText/vNeedleChars (strings). Complementary span: state how many chars of string vText there are before we see a char that is in the char list string vNeedleChars. AutoHotkey: ___ C++: std::strcspn [also: wcscspn] C#: ___ Crystal: ___ Excel: ___ Excel VBA: ___ Go: ___ Java: ___ JavaScript: ___ Kotlin: ___ PHP: strcspn Python: ___ R: ___ Ruby: ___ Rust: ___ Scala: ___ SQL (MySQL): ___ SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: ___ UFL: (CharIsDigitCountDemo) [count the number of chars considered digits][e.g. in the examples below, all reported count 10] Prompt: MyLang, one-liner. Count the number of chars in codepoints 0 to 127 inclusive considered digits. AutoHotkey: ___ [can use: IsDigit(Chr(vOrd))] C++: ___ [can use: isdigit(vChar)] C#: Console.WriteLine(Enumerable.Range(0, 128).Count(v=>Char.IsAsciiDigit((char)v))) [requires: using System.Linq] [also: Char.IsDigit] [WARNING (Enumerable.Range): 2nd param is count, not end] Crystal: p (0..127).count{|v| v.chr.ascii_number?} Excel: ___ Excel VBA: ___ Go: ___ [can use: vCount := 0; for i := 0; i <= 127; i++ {if unicode.IsDigit(rune(i)) {vCount++}}; fmt.Println(vCount)] Java: System.out.println(IntStream.rangeClosed(0, 127).filter(v->Character.isDigit(v)).count()) [requires: import java.util.stream.*] JavaScript: ___ Kotlin: println((0..127).count{Character.isDigit(it)}) PHP: var_dump(count(array_values(array_filter(range(0, 127), fn($v)=>ctype_digit(mb_chr($v)))))) Python: print(len(list(filter(lambda v:chr(v).isdigit(), range(0, 127+1))))) [also: print(sum(1 for v in range(0, 127+1) if chr(v).isdigit()))] R: ___ Ruby: ___ Rust: println!("{:?}", (0..=127).filter(|v| char::from_u32(*v as u32).unwrap().is_ascii_digit()).count()) Scala: println(Range.inclusive(0, 127).count(Character.isDigit(_))) SQL (MySQL): ___ SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: print((0...127).filter{Character(UnicodeScalar($0)!).isNumber}.count) UFL: (CharIsAlphaCountDemo) [count the number of chars considered letters][e.g. in the examples below, all reported count 52 (i.e. 26*2)] Prompt: MyLang, one-liner. Count the number of chars in codepoints 0 to 127 inclusive considered letters. AutoHotkey: ___ [can use: IsAlpha(Chr(vOrd))] C++: ___ [can use: isalpha(vChar)] C#: Console.WriteLine(Enumerable.Range(0, 128).Count(v=>Char.IsAsciiLetter((char)v))) [requires: using System.Linq] [also: Char.IsLetter] [WARNING (Enumerable.Range): 2nd param is count, not end] Crystal: p (0..127).count{|v| v.chr.ascii_letter?} Excel: ___ Excel VBA: ___ Go: ___ [can use: vCount := 0; for i := 0; i <= 127; i++ {if unicode.IsLetter(rune(i)) {vCount++}}; fmt.Println(vCount)] Java: System.out.println(IntStream.rangeClosed(0, 127).filter(v->Character.isLetter(v)).count()) [requires: import java.util.stream.*] JavaScript: ___ Kotlin: println((0..127).count{Character.isLetter(it)}) PHP: var_dump(count(array_values(array_filter(range(0, 127), fn($v)=>ctype_alpha(mb_chr($v)))))) Python: print(len(list(filter(lambda v:chr(v).isalpha(), range(0, 127+1))))) R: ___ Ruby: ___ Rust: println!("{:?}", (0..=127).filter(|v| char::from_u32(*v as u32).unwrap().is_ascii_alphabetic()).count()) Scala: println(Range.inclusive(0, 127).count(Character.isLetter(_))) SQL (MySQL): ___ SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: print((0...127).filter{Character(UnicodeScalar($0)!).isLetter}.count) UFL: (StrIsAlnumRegExDemo) [string contains ASCII letter chars (A-Z/a-z) and/or digits (0-9) only, string can be blank, check via RegEx][WARNING: some allow non-ASCII letters][see also: RegExContains/RegExEquals] Prompt: MyLang, one-liner, input var vText (string), output var vIsAlnum (bool). Return vIsAlnum, RegEx code to check whether or not vText contains ASCII letters and/or ASCII digits only (A-Z/a-z/0-9), blank string returns true. AutoHotkey: vIsAlnum := RegExMatch(vText, "^[A-Za-z0-9]*$") C++: vIsAlnum = std::regex_search(vText, std::regex("^[A-Za-z0-9]*$")) [requires: #include <regex>] C#: vIsAlnum = Regex.Match(vText, "^[A-Za-z0-9]*$").Success [requires: using System.Text.RegularExpressions] Crystal: vIsAlnum = /^[A-Za-z0-9]*$/.matches?(vText) [also: vIsAlnum = Regex.new("^[A-Za-z0-9]*$").matches?(vText)] [also: vIsAlnum = (vText.index(Regex.new("^[A-Za-z0-9]*$")) != nil)] [also: vIsAlnum = ((vText =~ Regex.new("^[A-Za-z0-9]*$")) != nil)] Excel: ___ Excel VBA: ___ [can use: Set oRegEx = CreateObject("VBScript.RegExp"): oRegEx.Pattern = "^[A-Za-z0-9]*$": vIsMatch = oRegEx.Test(vText)] Go: vIsAlnum := regexp.MustCompile("^[A-Za-z0-9]*$").MatchString(vText) Java: vIsAlnum = Pattern.compile("^[A-Za-z0-9]*$").matcher(vText).find() [requires: import java.util.regex.Pattern] JavaScript: vIsAlnum = /^[A-Za-z0-9]*$/.test(vText) [also: vIsAlnum = new RegExp("^[A-Za-z0-9]*$").test(vText)] Kotlin: vIsAlnum = Regex("^[A-Za-z0-9]*$").containsMatchIn(vText) [also: vIsAlnum = (Regex("^[A-Za-z0-9]*$").find(vText) != null)] PHP: $vIsAlnum = !!preg_match("/^[A-Za-z0-9]*$/", $vText) Python: vIsAlnum = (re.compile("^[A-Za-z0-9]*$").search(vText) != None) [requires: import re] R: vIsAlnum = grepl("^[A-Za-z0-9]*$", vText) Ruby: vIsAlnum = /^[A-Za-z0-9]*$/.match?(vText) [also: vIsAlnum = Regexp.new("^[A-Za-z0-9]*$").match?(vText)] [also: vIsAlnum = (vText.index(Regexp.new("^[A-Za-z0-9]*$")) != nil)] [also: vIsAlnum = ((vText =~ Regexp.new("^[A-Za-z0-9]*$")) != nil)] Rust: vIsAlnum = Regex::new("^[A-Za-z0-9]*$").unwrap().is_match(vText) [also: vIsAlnum = Regex::new("^[A-Za-z0-9]*$").unwrap().find(vText).is_some()] [requires: use regex::Regex] Scala: vIsAlnum = "^[A-Za-z0-9]*$".r.findFirstIn(vText).isDefined SQL (MySQL): ___ [can use: regexp_like(MyText, '^[A-Za-z0-9]*$')] SQL (PostgreSQL): ___ [can use: regexp_like(MyText, '^[A-Za-z0-9]*$')] SQL (SQLite): ___ [can use (GLOB, not RegEx): NOT glob('*[^A-Za-z0-9]*', MyText)] Swift: var oMatch = try Regex("^[A-Za-z0-9]*$").firstMatch(in:vText); var vIsAlnum = (oMatch != nil) UFL: StrIsDigit [string contains ASCII digit chars (0-9) only, string can be blank][WARNING: some allow non-ASCII digits][see also: RegExContains/RegExEquals] Prompt: MyLang, one-liner, input var vText (string), output var vIsDigit (bool). Return whether or not vText consists only of ASCII digits, blank string returns true. AutoHotkey: IsDigit [e.g. vIsDigit := IsDigit(vText)] [also (0-9A-Fa-f, and '0x'/'0X' prefix tolerated if present): IsXDigit(vText)] C++: ___ [can use: vIsDigit = std::regex_search(vText, std::regex("^\\d*$"))] [requires: #include <regex>] C#: ___ [can use: vIsDigit = vText.All(v=>Char.IsAsciiDigit(v))] [requires (All): using System.Linq] [also: Char.IsDigit] Crystal: ___ [can use: vIsDigit = vText.chars.all?{|v|v.ascii_number?}] [also: vText.codepoints.all?{|v|(48..57)===v}] Excel: ___ [can use: =ISNUMBER(VALUE(A1))] [WARNING: works correctly for 1-char strings, but for longer strings accepts '-'/'.' etc also] Excel VBA: ___ [can use (for first char of string): vIsDigit = (vText Like "#*")] [WARNING: '*' in Excel VBA is equivalent to '.*' in RegEx] Go: ___ [can use: vIsDigit := regexp.MustCompile("^\\d*$").MatchString(vText)] Java: ___ [can use: vIsDigit = vText.chars().allMatch(v->Character.isDigit(v))] JavaScript: ___ [can use: vIsDigit = /^\d*$/.test(vText)] Kotlin: ___ [can use: vIsDigit = vText.toCharArray().all{v->v.isDigit() && v.code<128}] PHP: ctype_digit [e.g. $vIsDigit = ctype_digit($vText)] [WARNING: a blank string returns false] Python: isdigit [e.g. vIsDigit = vText.isdigit()] [WARNING: a blank string returns false] R: ___ [can use: vIsDigit = grepl("^\\d*$", vText)] Ruby: ___ [can use: vIsDigit = vText.codepoints.all?{|v|(48..57)===v}] Rust: ___ [can use: vIsDigit = vText.chars().all(|v|v.is_ascii_digit())] Scala: ___ [can use: vIsDigit = vText.forall(Character.isDigit)] [also (alternate syntax): vText forall Character.isDigit] SQL (MySQL): ___ [can use: regexp_like(MyText, '^\\d*$')] SQL (PostgreSQL): ___ [can use: regexp_like(MyText, '^\d*$')] SQL (SQLite): ___ [can use: NOT glob('*[^0-9]*', MyText)] Swift: ___ [can use: vIsDigit = vText.allSatisfy{$0.isNumber}] UFL: CharIsDigit [char is an ASCII digit (0-9)][WARNING: some allow non-ASCII digits] Prompt: MyLang, one-liner, input var vChar (char or string), output var vIsDigit (bool). Return whether or not vChar is an ASCII digit. AutoHotkey: IsDigit [e.g. (for strings): vIsDigit := IsDigit(vText)] C++: isdigit [e.g. vIsDigit = isdigit(vChar)] C#: Char.IsAsciiDigit [e.g. vIsDigit = Char.IsAsciiDigit(vChar)] [also: Char.IsDigit] Crystal: ascii_number [e.g. vIsDigit = vChar.ascii_number?] Excel: ___ [can use (for strings): =ISNUMBER(VALUE(A1))] [WARNING: works consistently with 1-char strings, but for longer strings accepts '-'/'.' etc also] Excel VBA: ___ [can use (for one-char string): vIsDigit = (vText Like "#")] Go: ___ [can use (for ints): vIsDigit := unicode.IsDigit(vOrd)] Java: Character.isDigit [e.g. vIsDigit = Character.isDigit(vChar)] JavaScript: ___ [can use (for strings): vIsDigit = /^\d$/.test(vText)] Kotlin: Character.isDigit [e.g. vIsDigit = Character.isDigit(vChar)] PHP: ctype_digit [e.g. (for strings): $vIsDigit = ctype_digit($vText)] [WARNING: a blank string returns false] Python: isdigit [e.g. (for strings): vIsDigit = vText.isdigit()] [WARNING: a blank string returns false] R: ___ [can use (for one-char string): vIsDigit = grepl("^\\d$", vText)] Ruby: ___ [can use (for strings): vIsDigit = ((48..57) === vText[vPos].ord)] Rust: is_ascii_digit [e.g. vIsDigit = vChar.is_ascii_digit()] [WARNING: is_digit allows digits *and letters*] Scala: Character.isDigit [e.g. vIsDigit = Character.isDigit(vChar)] SQL (MySQL): ___ [can use (for strings): regexp_like(MyText, '^\\d*$')] SQL (PostgreSQL): ___ [can use (for strings): regexp_like(MyText, '^\d*$')] SQL (SQLite): ___ [can use (for strings): NOT glob('*[^0-9]*', MyText)] Swift: isNumber [e.g. vIsDigit = vChar.isNumber] UFL: StrIsAlpha [string contains ASCII letter chars (A-Z/a-z) only, string can be blank][WARNING: some allow non-ASCII letters][see also: RegExContains/RegExEquals] Prompt: MyLang, one-liner, input var vText (string), output var vIsAlpha (bool). Return whether or not vText consists only of ASCII letters, blank string returns true. AutoHotkey: IsAlpha [e.g. vIsAlpha := IsAlpha(vText)] C++: ___ [can use: vIsAlpha = std::regex_search(vText, std::regex("^[A-Za-z]*$"))] [requires: #include <regex>] C#: ___ [can use: vIsAlpha = vText.All(v=>Char.IsAsciiLetter(v))] [requires (All): using System.Linq] [also: Char.IsLetter] Crystal: ___ [can use: vIsAlpha = vText.chars.all?{|v|v.ascii_letter?}] [also: vText.codepoints.all?{|v|(97..122)===v || (65..90)===v}] Excel: ___ [can use (for first char of string): =AND(CODE(LOWER(A1))>=97,CODE(LOWER(A1))<=122)] Excel VBA: ___ [can use (for first char of string): vIsAlpha = (vText Like "[A-Za-z]*")] [WARNING: '*' in Excel VBA is equivalent to '.*' in RegEx] Go: ___ [can use: vIsAlpha := regexp.MustCompile("^[A-Za-z]*$").MatchString(vText)] Java: ___ [can use: vIsAlpha = vText.chars().allMatch(v->Character.isLetter(v))] JavaScript: ___ [can use: vIsAlpha = /^[A-Za-z]*$/.test(vText)] Kotlin: ___ [can use: vIsAlpha = vText.toCharArray().all{v->v.isLetter() && v.code<128}] PHP: ctype_alpha [e.g. $vIsAlpha = ctype_alpha($vText)] [WARNING: a blank string returns false] Python: isalpha [e.g. vIsAlpha = vText.isalpha()] [WARNING: a blank string returns false] R: ___ [can use: vIsAlpha = grepl("^[A-Za-z]*$", vText)] Ruby: ___ [can use: vIsAlpha = vText.codepoints.all?{|v|(97..122)===v || (65..90)===v}] Rust: ___ [can use: vIsAlpha = vText.chars().all(|v|v.is_ascii_alphabetic())] Scala: ___ [can use: vIsAlpha = vText.forall(Character.isLetter)] [also (alternate syntax): vText forall Character.isLetter] SQL (MySQL): ___ [can use: regexp_like(MyText, '^[A-Za-z]*$')] SQL (PostgreSQL): ___ [can use: regexp_like(MyText, '^[A-Za-z]*$')] SQL (SQLite): ___ [can use: NOT glob('*[^A-Za-z]*', MyText)] Swift: ___ [can use: vIsAlpha = vText.allSatisfy{$0.isLetter}] UFL: CharIsAlpha [char is an ASCII letter (A-Z/a-z)][WARNING: some allow non-ASCII letters] Prompt: MyLang, one-liner, input var vChar (char or string), output var vIsAlpha (bool). Return whether or not vChar is an ASCII letter. AutoHotkey: IsAlpha [e.g. (for strings): vIsAlpha := IsAlpha(vText)] C++: isalpha [e.g. vIsAlpha = isalpha(vChar)] C#: Char.IsAsciiLetter [e.g. vIsAlpha = Char.IsAsciiLetter(vChar)] [also: Char.IsLetter] Crystal: ascii_letter [e.g. vIsAlpha = vChar.ascii_letter?] Excel: ___ [can use (for first char of string): =AND(CODE(LOWER(A1))>=97,CODE(LOWER(A1))<=122)] Excel VBA: ___ [can use (for one-char string): vIsAlpha = (vText Like "[A-Za-z]")] Go: ___ [can use (for ints): vIsAlpha := unicode.IsLetter(vOrd)] Java: Character.isLetter [e.g. vIsAlpha = Character.isLetter(vChar)] JavaScript: ___ [can use (for strings): vIsAlpha = /^[A-Za-z]$/.test(vText)] Kotlin: Character.isLetter [e.g. vIsAlpha = Character.isLetter(vChar)] PHP: ctype_alpha [e.g. (for strings): $vIsAlpha = ctype_alpha($vText)] [WARNING: a blank string returns false] Python: isalpha [e.g. (for strings): vIsAlpha = vText.isalpha()] [WARNING: a blank string returns false] R: ___ [can use (for one-char string): vIsAlpha = grepl("^[A-Za-z]$", vText)] Ruby: ___ [can use (for strings): vIsAlpha = ((97..122) === vText[vPos].ord || (65..90) === vText[vPos].ord)] Rust: is_ascii_alphabetic [e.g. vIsAlpha = vChar.is_ascii_alphabetic()] Scala: Character.isLetter [e.g. vIsAlpha = Character.isLetter(vChar)] SQL (MySQL): ___ [can use (for strings): regexp_like(MyText, '^[A-Za-z]*$')] SQL (PostgreSQL): ___ [can use (for strings): regexp_like(MyText, '^[A-Za-z]*$')] SQL (SQLite): ___ [can use (for strings): NOT glob('*[^A-Za-z]*', MyText)] Swift: isLetter [e.g. vIsAlpha = vChar.isLetter] UFL: (StrIsUpper) [string contains upper-case ASCII letter chars (A-Z) only, string can be blank][WARNING: some allow non-ASCII letters][note: this differs from: vText == StrUpper(vText)][see also: RegExContains/RegExEquals] Prompt: MyLang, one-liner, input var vText (string), output var vIsUpper (bool). Return whether or not vText consists only of upper-case ASCII letters, blank string returns true. AutoHotkey: IsUpper [e.g. vIsUpper := IsUpper(vText)] C++: ___ [can use: vIsUpper = std::regex_search(vText, std::regex("^[A-Z]*$"))] [requires: #include <regex>] C#: ___ [can use: vIsUpper = vText.All(v=>Char.IsAsciiLetterUpper(v))] [requires (All): using System.Linq] [also: Char.IsUpper] Crystal: ___ [can use: vIsUpper = vText.chars.all?{|v|v.ascii_uppercase?}] [also: vText.codepoints.all?{|v|(65..90)===v}] Excel: ___ [can use (for first char of string): =AND(CODE(A1)>=65,CODE(A1)<=90)] Excel VBA: ___ [can use (for first char of string): vIsUpper = (vText Like "[A-Z]*")] [WARNING: '*' in Excel VBA is equivalent to '.*' in RegEx] [WARNING: case-insensitive if use 'Option Compare Text'] Go: ___ [can use: vIsUpper := regexp.MustCompile("^[A-Z]*$").MatchString(vText)] Java: ___ [can use: vIsUpper = vText.chars().allMatch(v->Character.isUpperCase(v))] JavaScript: ___ [can use: vIsUpper = /^[A-Z]*$/.test(vText)] Kotlin: ___ [can use: vIsUpper = vText.toCharArray().all{v->v.isUpperCase() && v.code<128}] PHP: ctype_upper [e.g. $vIsUpper = ctype_upper($vText)] [WARNING: a blank string returns false] Python: ___ [can use: vIsUpper = (vText.isalpha() and vText.isupper())] [WARNING (isalpha/isupper): a blank string returns false] [also: vIsUpper = (re.fullmatch("^[A-Z]*$", vText) != None)] [WARNING: isupper: 'True if all cased characters in the string are uppercase and there is at least one cased character'] R: ___ [can use: vIsUpper = grepl("^[A-Z]*$", vText)] Ruby: ___ [can use: vIsUpper = vText.codepoints.all?{|v|(65..90)===v}] Rust: ___ [can use: vIsUpper = vText.chars().all(|v|v.is_ascii_uppercase())] Scala: ___ [can use: vIsUpper = vText.forall(Character.isUpperCase)] [also (alternate syntax): vText forall Character.isUpperCase] SQL (MySQL): ___ [can use: regexp_like(MyText, '^[A-Z]*$' COLLATE utf8mb4_bin)] SQL (PostgreSQL): ___ [can use: regexp_like(MyText, '^[A-Z]*$')] SQL (SQLite): ___ [can use: NOT glob('*[^A-Z]*', MyText)] Swift: ___ [can use: vIsUpper = vText.allSatisfy{$0.isUppercase}] UFL: (CharIsUpper) [char is an upper-case ASCII letter (A-Z)][WARNING: some allow non-ASCII letters] Prompt: MyLang, one-liner, input var vChar (char or string), output var vIsUpper (bool). Return whether or not vChar is an upper-case ASCII letter. AutoHotkey: IsUpper [e.g. (for strings): vIsUpper := IsUpper(vText)] C++: isupper [e.g. vIsUpper = isupper(vChar)] C#: Char.IsAsciiLetterUpper [e.g. vIsUpper = Char.IsAsciiLetterUpper(vChar)] [also: Char.IsUpper] Crystal: ascii_uppercase [e.g. vIsUpper = vChar.ascii_uppercase?] [also (for strings): vIsUpper = ((65..90) === vText[vPos].ord)] Excel: ___ [can use (for first char of string): =AND(CODE(A1)>=65,CODE(A1)<=90)] Excel VBA: ___ [can use (for one-char string): vIsUpper = (vText Like "[A-Z]")] [WARNING: case-insensitive if use 'Option Compare Text'] Go: unicode.IsUpper [can use (for ints): vIsUpper := unicode.IsUpper(vOrd)] Java: Character.isUpperCase [e.g. vIsUpper = Character.isUpperCase(vChar)] JavaScript: ___ [can use (for strings): vIsUpper = /^[A-Z]$/.test(vText)] Kotlin: Character.isUpperCase [e.g. vIsUpper = Character.isUpperCase(vChar)] PHP: ctype_upper [e.g. (for strings): $vIsUpper = ctype_upper($vText)] [WARNING: a blank string returns false] Python: ___ [can use (for strings): vIsUpper = (vText.isalpha() and vText.isupper())] [WARNING (isalpha/isupper): a blank string returns false] [also: vIsUpper = (re.fullmatch("^[A-Z]*$", vText) != None)] [WARNING: isupper: 'True if all cased characters in the string are uppercase and there is at least one cased character'] R: ___ [can use (for one-char string): vIsUpper = grepl("^[A-Z]$", vText)] Ruby: ___ [can use (for strings): vIsUpper = ((65..90) === vText[vPos].ord)] Rust: is_ascii_uppercase [e.g. vIsUpper = vChar.is_ascii_uppercase()] Scala: Character.isUpperCase [e.g. vIsUpper = Character.isUpperCase(vChar)] SQL (MySQL): ___ [can use (for strings): regexp_like(MyText, '^[A-Z]*$' COLLATE utf8mb4_bin)] SQL (PostgreSQL): ___ [can use (for strings): regexp_like(MyText, '^[A-Z]*$')] SQL (SQLite): ___ [can use (for strings): NOT glob('*[^A-Z]*', MyText)] Swift: isUppercase [e.g. vIsUpper = vChar.isUppercase] UFL: (StrIsLower) [string contains lower-case ASCII letter chars (a-z) only, string can be blank][WARNING: some allow non-ASCII letters][note: this differs from: vText == StrLower(vText)][see also: RegExContains/RegExEquals] Prompt: MyLang, one-liner, input var vText (string), output var vIsLower (bool). Return whether or not vText consists only of lower-case ASCII letters, blank string returns true. AutoHotkey: IsLower [e.g. vIsLower := IsLower(vText)] C++: ___ [can use: vIsLower = std::regex_search(vText, std::regex("^[a-z]*$"))] [requires: #include <regex>] C#: ___ [can use: vIsLower = vText.All(v=>Char.IsAsciiLetterLower(v))] [requires (All): using System.Linq] [also: Char.IsLower] Crystal: ___ [can use: vIsLower = vText.chars.all?{|v|v.ascii_lowercase?}] [also: vText.codepoints.all?{|v|(97..122)===v}] Excel: ___ [can use (for first char of string): =AND(CODE(A1)>=97,CODE(A1)<=122)] Excel VBA: ___ [can use (for first char of string): vIsLower = (vText Like "[a-z]*")] [WARNING: '*' in Excel VBA is equivalent to '.*' in RegEx] [WARNING: case-insensitive if use 'Option Compare Text'] Go: ___ [can use: vIsLower := regexp.MustCompile("^[a-z]*$").MatchString(vText)] Java: ___ [can use: vIsLower = vText.chars().allMatch(v->Character.isLowerCase(v))] JavaScript: ___ [can use: vIsLower = /^[a-z]*$/.test(vText)] Kotlin: ___ [can use: vIsLower = vText.toCharArray().all{v->v.isLowerCase() && v.code<128}] PHP: ctype_lower [e.g. $vIsLower = ctype_lower($vText)] [WARNING: a blank string returns false] Python: ___ [can use: vIsLower = (vText.isalpha() and vText.islower())] [WARNING (isalpha/islower): a blank string returns false] [also: vIsLower = (re.fullmatch("^[a-z]*$", vText) != None)] [WARNING: islower: 'True if all cased characters in the string are lowercase and there is at least one cased character'] R: ___ [can use: vIsLower = grepl("^[a-z]*$", vText)] Ruby: ___ [can use: vIsLower = vText.codepoints.all?{|v|(97..122)===v}] Rust: ___ [can use: vIsLower = vText.chars().all(|v|v.is_ascii_lowercase())] Scala: ___ [can use: vIsLower = vText.forall(Character.isLowerCase)] [also (alternate syntax): vText forall Character.isLowerCase] SQL (MySQL): ___ [can use: regexp_like(MyText, '^[a-z]*$' COLLATE utf8mb4_bin)] SQL (PostgreSQL): ___ [can use: regexp_like(MyText, '^[a-z]*$')] SQL (SQLite): ___ [can use: NOT glob('*[^a-z]*', MyText)] Swift: ___ [can use: vIsLower = vText.allSatisfy{$0.isLowercase}] UFL: (CharIsLower) [char is a lower-case ASCII letter (a-z)][WARNING: some allow non-ASCII letters] Prompt: MyLang, one-liner, input var vChar (char or string), output var vIsLower (bool). Return whether or not vChar is a lower-case ASCII letter. AutoHotkey: IsLower [e.g. (for strings): vIsLower := IsLower(vText)] C++: islower [e.g. vIsLower = islower(vChar)] C#: Char.IsAsciiLetterLower [e.g. vIsLower = Char.IsAsciiLetterLower(vChar)] [also: Char.IsLower] Crystal: ascii_lowercase [e.g. vIsLower = vChar.ascii_lowercase?] [also (for strings): vIsLower = ((97..122) === vText[vPos].ord)] Excel: ___ [can use (for first char of string): =AND(CODE(A1)>=97,CODE(A1)<=122)] Excel VBA: ___ [can use (for one-char string): vIsLower = (vText Like "[a-z]")] [WARNING: case-insensitive if use 'Option Compare Text'] Go: unicode.IsLower [can use (for ints): vIsLower := unicode.IsLower(vOrd)] Java: Character.isLowerCase [e.g. vIsLower = Character.isLowerCase(vChar)] JavaScript: ___ [can use (for strings): vIsLower = /^[a-z]$/.test(vText)] Kotlin: Character.isLowerCase [e.g. vIsLower = Character.isLowerCase(vChar)] PHP: ctype_lower [e.g. (for strings): $vIsLower = ctype_lower($vText)] [WARNING: a blank string returns false] Python: ___ [can use (for strings): vIsLower = (vText.isalpha() and vText.islower())] [WARNING (isalpha/islower): a blank string returns false] [also: vIsLower = (re.fullmatch("^[a-z]*$", vText) != None)] [WARNING: islower: 'True if all cased characters in the string are lowercase and there is at least one cased character'] R: ___ [can use (for one-char string): vIsLower = grepl("^[a-z]$", vText)] Ruby: ___ [can use (for strings): vIsLower = ((97..122) === vText[vPos].ord)] Rust: is_ascii_lowercase [e.g. vIsLower = vChar.is_ascii_lowercase()] Scala: Character.isLowerCase [e.g. vIsLower = Character.isLowerCase(vChar)] SQL (MySQL): ___ [can use (for strings): regexp_like(MyText, '^[a-z]*$' COLLATE utf8mb4_bin)] SQL (PostgreSQL): ___ [can use (for strings): regexp_like(MyText, '^[a-z]*$')] SQL (SQLite): ___ [can use (for strings): NOT glob('*[^a-z]*', MyText)] Swift: isLowercase [e.g. vIsLower = vChar.isLowercase] UFL: (StrIsAlnum) [string contains ASCII letter chars (A-Z/a-z) and/or digits (0-9) only, string can be blank][WARNING: some allow non-ASCII letters][see also: RegExContains/RegExEquals/StrIsAlnumRegExDemo] Prompt: MyLang, one-liner, input var vText (string), output var vIsAlnum (bool). Return whether or not vText consists only of ASCII letters/ASCII digits, blank string returns true. AutoHotkey: IsAlnum [e.g. vIsAlnum := IsAlnum(vText)] C++: ___ [can use: vIsAlnum = std::regex_search(vText, std::regex("^[A-Za-z0-9]*$"))] [requires: #include <regex>] C#: ___ [can use: vIsAlnum = vText.All(v=>Char.IsAsciiLetterOrDigit(v))] [requires (All): using System.Linq] [also: Char.IsLetterOrDigit] Crystal: ___ [can use: vIsAlnum = vText.chars.all?{|v|v.ascii_alphanumeric?}] [also: vText.codepoints.all?{|v|(97..122)===v || (65..90)===v || (48..57)===v}] Excel: ___ Excel VBA: ___ [can use (for first char of string): vIsAlnum = (vText Like "[A-Za-z0-9]*")] [WARNING: '*' in Excel VBA is equivalent to '.*' in RegEx] Go: ___ [can use: vIsAlnum := regexp.MustCompile("^[A-Za-z0-9]*$").MatchString(vText)] Java: ___ [can use: vIsAlnum = vText.chars().allMatch(v->Character.isLetterOrDigit(v))] JavaScript: ___ [can use: vIsAlnum = /^[A-Za-z0-9]*$/.test(vText)] Kotlin: ___ [can use: vIsAlnum = vText.toCharArray().all{v->v.isLetterOrDigit() && v.code<128}] PHP: ctype_alnum [e.g. $vIsAlnum = ctype_alnum($vText)] [WARNING: a blank string returns false] Python: isalnum [e.g. vIsAlnum = vText.isalnum()] [WARNING: a blank string returns false] R: ___ [can use: vIsAlnum = grepl("^[A-Za-z0-9]*$", vText)] Ruby: ___ [can use: vIsAlnum = vText.codepoints.all?{|v|(97..122)===v || (65..90)===v || (48..57)===v}] Rust: ___ [can use: vIsAlnum = vText.chars().all(|v|v.is_ascii_alphanumeric())] Scala: ___ [can use: vIsAlnum = vText.forall(Character.isLetterOrDigit)] [also (alternate syntax): vText forall Character.isLetterOrDigit] SQL (MySQL): ___ [can use: regexp_like(MyText, '^[A-Za-z0-9]*$')] SQL (PostgreSQL): ___ [can use: regexp_like(MyText, '^[A-Za-z0-9]*$')] SQL (SQLite): ___ [can use: NOT glob('*[^A-Za-z0-9]*', MyText)] Swift: ___ [can use: vIsAlnum = vText.allSatisfy{CharacterSet.alphanumerics.contains($0.unicodeScalars.first!)}] [requires: import Foundation] UFL: (CharIsAlnum) [char is an ASCII letter (A-Z/a-z) or a digit (0-9)][WARNING: some allow non-ASCII letters] Prompt: MyLang, one-liner, input var vChar (char or string), output var vIsAlnum (bool). Return whether or not vChar is an ASCII letter/ASCII digit. AutoHotkey: IsAlnum [e.g. (for strings): vIsAlnum := IsAlnum(vText)] C++: isalnum [e.g. vIsAlnum = isalnum(vChar)] C#: Char.IsAsciiLetterOrDigit [e.g. vIsAlnum = Char.IsAsciiLetterOrDigit(vChar)] [also: Char.IsLetterOrDigit] Crystal: ascii_alphanumeric [e.g. vIsAlnum = vChar.ascii_alphanumeric?] [also (for strings): vIsAlnum = ((97..122) === vText[vPos].ord || (65..90) === vText[vPos].ord || (48..57) === vText[vPos].ord)] Excel: ___ Excel VBA: ___ [can use (for one-char string): vIsAlnum = (vText Like "[A-Za-z0-9]")] Go: ___ [can use (for ints): vIsAlnum := (unicode.IsLetter(vOrd) || unicode.IsDigit(vOrd))] Java: Character.isLetterOrDigit [e.g. vIsAlnum = Character.isLetterOrDigit(vChar)] JavaScript: ___ [can use (for strings): vIsAlnum = /^[A-Za-z0-9]$/.test(vText)] Kotlin: Character.isLetterOrDigit [e.g. vIsAlnum = Character.isLetterOrDigit(vChar)] PHP: ctype_alnum [e.g. (for strings): $vIsAlnum = ctype_alnum($vText)] [WARNING: a blank string returns false] Python: isalnum [e.g. (for strings): vIsAlnum = vText.isalnum()] [WARNING: a blank string returns false] R: ___ [can use (for one-char string): vIsAlnum = grepl("^[A-Za-z0-9]$", vText)] Ruby: ___ [can use (for strings): vIsAlnum = ((97..122) === vText[vPos].ord || (65..90) === vText[vPos].ord || (48..57) === vText[vPos].ord)] Rust: is_ascii_alphanumeric [e.g. vIsAlnum = vChar.is_ascii_alphanumeric()] Scala: Character.isLetterOrDigit [e.g. vIsAlnum = Character.isLetterOrDigit(vChar)] SQL (MySQL): ___ [can use (for strings): regexp_like(MyText, '^[A-Za-z0-9]*$')] SQL (PostgreSQL): ___ [can use (for strings): regexp_like(MyText, '^[A-Za-z0-9]*$')] SQL (SQLite): ___ [can use (for strings): NOT glob('*[^A-Za-z0-9]*', MyText)] Swift: ___ [can use: vIsAlnum = CharacterSet.alphanumerics.contains(vChar.unicodeScalars.first!)] [requires: import Foundation] UFL: StrIsAscii [string contains ASCII chars (0-127) only, string can be blank][see also: RegExContains/RegExEquals/CharIsAscii] Prompt: MyLang, one-liner, input var vText (string), output var vIsAscii (bool). Return whether or not vText consists only of ASCII characters, blank string returns true. AutoHotkey: ___ [can use: vIsAscii := !RegExMatch(vText, "[^[:ascii:]]")] [also (if convert Unicode to codepade 20127, us-ascii, if a non-ASCII char is seen, a default char is used): vUsedDefaultChar := 0, DllCall("kernel32\WideCharToMultiByte", "UInt",20127, "UInt",0x400, "Ptr",StrPtr(vText), "Int",StrLen(vText), "Ptr",0, "Int",0, "Ptr",0, "Int*",&vUsedDefaultChar), vIsAcsii := !vUsedDefaultChar] C++: ___ [can use: vIsAscii = !std::regex_search(vText, std::regex("[^\\x00-\\x7F]"))] [requires: #include <regex>] C#: ___ [can use: vIsAscii = vText.All(v=>Char.IsAscii(v))] [requires (All): using System.Linq] Crystal: ascii_only [e.g. vIsAscii = vText.ascii_only?] Excel: ___ [can use (for first char of string): =CODE(A1)<128] Excel VBA: ___ [can use (for first char of string): vIsAscii = (AscW(vText) < 128)] Go: ___ [can use: vIsAscii := !regexp.MustCompile("[^\x00-\x7F]").MatchString(vText)] [note: both of these work: '\x' (string literal), '\\x' (RegEx formatting)] Java: ___ [can use: vIsAscii = vText.chars().allMatch(v->v<128)] JavaScript: ___ [can use: vIsAscii = !/[^\x00-\x7F]/.test(vText)] Kotlin: ___ [can use: vIsAscii = vText.toCharArray().all{v->v.code<128}] PHP: ___ [can use: $vIsAscii = !preg_match("/[^\x00-\x7F]/", $vText)] [also: $vIsAscii = mb_check_encoding($vText, "ASCII")] [note: both of these work: '\x' (string literal), '\\x' (RegEx formatting)] Python: isascii [e.g. vIsAscii = vText.isascii()] [note: a blank string returns true (unlike various other 'is' methods, e.g. isdigit/isalpha/isalnum)] R: ___ [can use: vIsAscii = all(utf8ToInt(vText) < 128)] [also: vIsAscii = !is.na(iconv(vText, to="ascii"))] [also: vIsAscii = !grepl("[^[:ascii:]]", vText)] [also: vIsAscii = !grepl("[^\\x00-\\x7F]", vText, perl=TRUE)] [also: showNonASCII(vText)] [WARNING (showNonASCII/iconv): 'this rendering depends on iconv(to = "ASCII") failing to convert, and macOS 14 no longer does so reliably so for example permille'] [note: '\x' (string literal) works with/without 'perl=TRUE', '\\x' (RegEx formatting) works with 'perl=TRUE', may work (not guaranteed to work) if omit 'perl=TRUE'] Ruby: ascii_only [e.g. vIsAscii = vText.ascii_only?] Rust: is_ascii [e.g. vIsAscii = vText.is_ascii()] Scala: ___ [can use: vIsAscii = vText.chars().allMatch(_<128)] SQL (MySQL): ___ [can use: NOT regexp_like(MyText, '[^\\x00-\\x7F]')] SQL (PostgreSQL): ___ [can use: NOT regexp_like(MyText, '[^\x00-\x7F]')] SQL (SQLite): ___ [can use: NOT glob('*[^'||char(1,45,127)||']*', MyText)] [note: char(45) is hyphen] Swift: ___ [can use: vIsAscii = (vText.utf8.count == vText.count)] [note: checks if UTF-8 byte count = codepoint count] [also: vIsAscii = vText.allSatisfy{$0.unicodeScalars.first!.value<128}] UFL: CharIsAscii [char is an ASCII char (0-127)][see also: StrIsAscii] Prompt: MyLang, one-liner, input var vChar (char or string), output var vIsAscii (bool). Return whether or not vChar is an ASCII character. AutoHotkey: ___ [can use (for first char of string): vIsAscii := (Ord(vText) < 128)] C++: isascii [e.g. vIsAscii = isascii(vChar)] C#: Char.IsAscii [e.g. vIsAscii = Char.IsAscii(vChar)] Crystal: ascii [e.g. vIsAscii = vChar.ascii?] Excel: ___ [can use (for first char of string): =CODE(A1)<128] Excel VBA: ___ [can use (for first char of string): vIsAscii = (AscW(vText) < 128)] Go: ___ [can use (for ints): vIsAscii := (vOrd <= unicode.MaxASCII)] Java: ___ [can use: vIsAscii = (vChar < 128)] JavaScript: ___ [can use (for strings): vIsAscii = /^[\x00-\x7F]$/.test(vChar)] [also (for first char of string): vIsAscii = (vText.codePointAt() < 128)] [also (for first char of string): vIsAscii = (vText.charCodeAt() < 128)] Kotlin: ___ [can use: vIsAscii = (vChar.code < 128)] PHP: ___ [can use (for first char of string): $vIsAscii = (mb_ord($vText) < 128)] Python: isascii [e.g. (for strings): vIsAscii = vText.isascii()] R: ___ [can use (for one-char string): vIsAscii = (utf8ToInt(vText) < 128)] Ruby: ascii_only [e.g. (for strings): vIsAscii = vText.ascii_only?] Rust: is_ascii [e.g. vIsAscii = vChar.is_ascii()] Scala: ___ [can use: vIsAscii = (vChar < 128)] SQL (MySQL): ___ [can use (for strings): NOT regexp_like(MyText, '[^\\x00-\\x7F]')] [can use (for first char of string): ord(MyText)<128] [MAJOR WARNING: ord() applies an unusual formula to the first 3 bytes] SQL (PostgreSQL): ___ [can use (for strings): NOT regexp_like(MyText, '[^\x00-\x7F]')] [can use (for first char of string): ascii(MyText)<128] SQL (SQLite): ___ [can use (for first char of string): unicode(MyText)<128] Swift: isASCII [e.g. vIsAscii = vChar.isASCII] UFL: (StrWrap) [e.g. replace some whitespace chars with line breaks, such that each line has a maximum length n] Prompt: MyLang, one-liner, input vars vText/vCount (string/int), output var vTextNew (string). Apply a maximum line length vCount by replacing occasional whitespace chars with line breaks. AutoHotkey: ___ C++: ___ C#: ___ Crystal: ___ Excel: ___ Excel VBA: ___ Go: ___ Java: ___ JavaScript: ___ Kotlin: ___ PHP: wordwrap [e.g. wordwrap($vText, $vCount)] Python: textwrap.fill [e.g. textwrap.fill(vText, vCount)] [note: textwrap.wrap() returns a list of lines] [requires: import textwrap] R: strwrap [e.g. strwrap(vText, width=vCount)] Ruby: ___ Rust: ___ Scala: ___ SQL (MySQL): ___ SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: ___ UFL: ChrUnused [or CharUnused][ChrUnused(oStrings*), return a char not present in oStrings*, e.g. ChrUnused("abc", "def", "ghi") returns Chr(1)][find chars to use as temporary delimiters, or placeholders when swapping strings] Prompt: MyLang, one-liner, input vars vText1/vText2/vText3 (strings). Return the character with the lowest codepoint, not present in those strings, as vText. E.g. ChrUnused("abc", "def", "ghi") would return Chr(1). AutoHotkey: ___ C++: ___ C#: ___ Crystal: ___ Excel: ___ Excel VBA: ___ Go: ___ Java: ___ JavaScript: ___ Kotlin: ___ PHP: ___ Python: ___ R: ___ Ruby: ___ Rust: ___ Scala: ___ SQL (MySQL): ___ SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: ___ UFL: (PathSplit) [or StrSplitPath][split a path to sub-elements e.g. dir/name/name-no-extension/extension][see also: StrSplit/RegExReplace/RegExIndex] Prompt: MyLang, one-liner, input var vPath (string), output vars vName/vDir/vExt/vNameNoExt (strings). Name/dir/extension/name-no-extension as vName/vDir/vExt/vNameNoExt respectively. AutoHotkey: SplitPath [e.g. SplitPath(vPath, &vName, &vDir, &vExt, &vNameNoExt)] [e.g. SplitPath(vPath,,,,, &vDrive)] C++: ___ C#: ___ Crystal: ___ Excel: ___ Excel VBA: ___ Go: ___ Java: ___ JavaScript: ___ Kotlin: ___ PHP: ___ Python: ___ R: ___ Ruby: ___ Rust: ___ Scala: ___ SQL (MySQL): ___ SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: ___ UFL: (StrToName) [or StrToFileName][webpage title to file name (no dir, no extension) (using the same rules as the web browser)][see also: StrTranslate] Prompt: MyLang, one-liner, input var vTitle (string), output var vNameNoExt (string). Webpage title to file name (no dir, no extension) (using the same rules as the web browser Chrome). AutoHotkey: ___ C++: ___ C#: ___ Crystal: ___ Excel: ___ Excel VBA: ___ Go: ___ Java: ___ JavaScript: ___ Kotlin: ___ PHP: ___ Python: ___ R: ___ Ruby: ___ Rust: ___ Scala: ___ SQL (MySQL): ___ SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: ___ UFL: (StrPrepend) [prepend string (modify string)] Prompt: MyLang, one-liner, input vars vText/vPfx (strings). Prepend vPfx to vText (modify string). AutoHotkey: ___ C++: ___ C#: ___ Crystal: ___ Excel: ___ Excel VBA: ___ Go: ___ Java: ___ JavaScript: ___ [can use: vText = vPfx + vText] Kotlin: ___ PHP: ___ Python: ___ R: ___ Ruby: prepend [e.g. vText.prepend(vPfx)] [WARNING: prepend() modifies the string] Rust: ___ Scala: ___ SQL (MySQL): ___ SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: ___ UFL: (StrInsert) [insert string (modify string)][add infix string][see also: RegExReplace/StrOverwritten] Prompt: MyLang, one-liner, input vars vText/vPos/vIfx (string/int/string). Insert vIfx into vText at vPos (modify string). AutoHotkey: ___ C++: ___ C#: ___ Crystal: ___ Excel: ___ Excel VBA: ___ Go: ___ Java: ___ JavaScript: ___ [can use: vText = vText.slice(0, vPos) + vIfx + vText.slice(vPos)] Kotlin: ___ PHP: ___ Python: ___ R: ___ Ruby: insert [e.g. vText.insert(vPos, vIfx)] Rust: ___ Scala: ___ SQL (MySQL): ___ SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: ___ UFL: (StrInserted) [insert string (modify string)][add infix string][note: equivalent to 'StrOverwritten' when 0 chars are deleted][see also: RegExReplace/StrOverwritten] Prompt: MyLang, one-liner, input vars vText/vPos/vIfx (string/int/string), output var vTextNew (string). Insert vIfx into vText at vPos (return new string). AutoHotkey: ___ C++: ___ C#: ___ Crystal: ___ Excel: ___ Excel VBA: WorksheetFunction.Replace [e.g. vTextNew = WorksheetFunction.Replace(vText, vPos, 0, vIfx)] [WARNING: 'Replace' is confusingly named, it works like an 'overwrite' function] Go: ___ Java: ___ JavaScript: ___ [can use: vTextNew = vText.slice(0, vPos) + vIfx + vText.slice(vPos)] Kotlin: ___ PHP: ___ Python: ___ [can use (slice assignment): oList = list(vText); oList[vPos:vPos] = vIfx; vTextNew = "".join(oList)] [e.g. oList = list("abcdefghij"); oList[5:5] = "------"; vTextNew = "".join(oList)] R: ___ Ruby: ___ Rust: ___ Scala: patch [e.g. vTextNew = vText.patch(vPos, vIfx, 0)] SQL (MySQL): insert [e.g. insert(MyText, MyPos, 0, MyIfx)] SQL (PostgreSQL): overlay [e.g. overlay(MyText PLACING MyIfx FROM MyPos FOR 0)] [e.g. overlay('abcdefghij' PLACING '------' FROM 6 FOR 0)] SQL (SQLite): ___ Swift: ___ UFL: (StrAppend) [append string (modify string)] Prompt: MyLang, one-liner, input vars vText/vSfx (strings). Append vSfx to vText (modify string). AutoHotkey: ___ [can use: .=] C++: ___ [can use: +=] C#: ___ [can use: +=] Crystal: ___ [can use: +=] Excel: ___ [can use: &] [e.g. =A1&B1] Excel VBA: ___ Go: ___ [can use: +=] Java: ___ [can use: +=] JavaScript: ___ [can use: +=] [e.g. vText += vSfx] Kotlin: ___ [can use: +=] PHP: ___ [can use: .=] Python: ___ [can use: +=] R: ___ [can use: vText = paste0(vText, vSfx)] [note: to append to every vector element: oVec = paste0(oVec, vSfx)] Ruby: ___ [can use: +=] [also: <<] [also: concat] [WARNING: concat() modifies the string] Rust: ___ [can use: +=] [also: vText.push_str(vSfx)] Scala: ___ [can use: +=] SQL (MySQL): ___ SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: ___ [can use: +=] [also: append] [WARNING: append() modifies the string] UFL: (StrOverwrite) [or StrSplice/StrRemoveAndInsert][overwrite string (modify string)][splice string][delete 0 or more chars, add infix string][often equivalent to a single string replacement][remove n chars (and shift chars left), and insert 0 or more chars][insert infix chars][see also: StrReplace/Array.Splice] Prompt: MyLang, one-liner, input vars vText/vPos/vCountDel/vIfx (string/int/int/string). Delete vCountDel chars at vPos, insert vIfx into vText at vPos (modify string). AutoHotkey: ___ C++: ___ C#: ___ Crystal: ___ Excel: ___ Excel VBA: ___ Go: ___ Java: ___ JavaScript: ___ [can use: vText = vText.slice(0, vPos) + vIfx + vText.slice(vPos + vCountDel)] Kotlin: ___ PHP: ___ Python: ___ R: ___ [can use: substr(vText, vPos1, vPos2) = vIfx] [WARNING: the number of chars overwritten is a max of vPos2-vPos1+1] Ruby: ___ [can use (setbyte): e.g. vText = "abcde"; vText.setbyte(2, "X".ord)] Rust: ___ Scala: ___ SQL (MySQL): ___ SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: ___ UFL: (StrOverwritten) [or StrSpliced/StrRemovedAndInserted][overwrite string (return new string)][splice string][delete 0 or more chars, add infix string][remove n chars (and shift chars left), and insert 0 or more chars][insert infix chars][see also: StrReplace/StrInserted/Array.Splice] Prompt: MyLang, one-liner, input vars vText/vPos/vCountDel/vIfx (string/int/int/string), output var vTextNew (string). Delete vCountDel chars at vPos, insert vIfx into vText at vPos (return new string). AutoHotkey: ___ C++: ___ C#: ___ Crystal: ___ Excel: REPLACE [e.g. =REPLACE(A1,MyPos,MyCountDel,MyIfx)] [WARNING: 'REPLACE' is confusingly named, it works like an 'overwrite' function] Excel VBA: WorksheetFunction.Replace [e.g. vTextNew = WorksheetFunction.Replace(vText, vPos, vCountDel, vIfx)] [WARNING: 'Replace' is confusingly named, it works like an 'overwrite' function] Go: ___ Java: ___ JavaScript: ___ [can use: vTextNew = vText.slice(0, vPos) + vIfx + vText.slice(vPos + vCountDel)] Kotlin: ___ PHP: ___ Python: ___ [can use (slice assignment): oList = list(vText); oList[vPos:vPos+vCountDel] = vIfx; vTextNew = "".join(oList)] [e.g. oList = list("abcdefghij"); oList[5:8] = "------"; vTextNew = "".join(oList)] R: ___ Ruby: ___ Rust: ___ Scala: patch [e.g. vTextNew = vText.patch(vPos, vIfx, vCountDel)] SQL (MySQL): insert [e.g. insert(MyText, MyPos, MyCountDel, MyIfx)] SQL (PostgreSQL): overlay [e.g. overlay(MyText PLACING MyIfx FROM MyPos FOR MyCountDel)] [e.g. overlay('abcdefghij' PLACING '------' FROM 6 FOR 3)] SQL (SQLite): ___ Swift: ___ UFL: (StrNext) [generate the next string e.g. 'abc' to 'abd', e.g. 'azz' to 'baa'][ideally: specify min/max values for each char via an object][see also: Array.Next] Prompt: MyLang, one-liner, input var vText (string), output var vTextNew (string). Generate the next string (e.g. 'abc' to 'abd', e.g. 'azz' to 'baa'). AutoHotkey: ___ C++: ___ C#: ___ Crystal: ___ [can use: succ] Excel: ___ Excel VBA: ___ Go: ___ Java: ___ JavaScript: ___ Kotlin: ___ PHP: ___ [can use: ++] [e.g. $vText++] [e.g. ++$vText] Python: ___ R: ___ Ruby: ___ [can use: succ] [alias (succ): next] [also (multiple strings): upto] Rust: ___ Scala: ___ SQL (MySQL): ___ SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: ___ UFL: (StrSurrogatePairDemo) [create an array containing the high surrogate and low surrogate for a Unicode character, as 2 separate strings][WARNING: many languages don't allow chr(n) for 0xD800-0xDBFF (high surrogates) or 0xDC00-0xDFFF (low surrogates)][e.g. '𝄞' is chr(0xD834, 0xDD1E)][see also: Array.CodepointsToShorts] Prompt: MyLang, one-liner, output var oArray (array). Create an array containing the high surrogate and low surrogate for the Unicode character Chr(119070), as 2 separate strings. AutoHotkey: oArray := StrSplit("𝄞", "") C++: ___ C#: oArray = Regex.Split("𝄞", "(?<=\\G.)(?!$)") Crystal: ___ Excel: ___ [can use: =MID("𝄞",1,1)&","&MID("𝄞",2,1)] Excel VBA: ___ [can use: oArray = Array(ChrW(55348), ChrW(56606))] [also: oArray = Array(ChrW(&HD834), ChrW(&HDD1E))] Go: ___ Java: oArray = "𝄞".split("") JavaScript: oArray = "𝄞".split("") Kotlin: oArray = "𝄞".chunked(1).toTypedArray() PHP: ___ Python: ___ R: ___ Ruby: ___ Rust: ___ Scala: oArray = "𝄞".split("") SQL (MySQL): ___ SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: ___

The Universal Function Library Project: Details

Notes: Function names, parameter names, parameter order, and functionality recommendations, are approximate suggestions; there may be good arguments for alternatives. Function names in parentheses are regarded as somewhat or considerably lower priority. Many example functions are available at JEE.js, the function library that powers this website. Pos parameters are intended to handle one or both of: integer (StartPos) and array ([StartPos, EndPos]). Where Pos is 1-based or 0-based depending on the programming language. CaseSen parameters are case-sensitive by default, but could accept a case-insensitive locale/standard. One simple case-insensitive standard would only treat A-Z/a-z as case-insensitive. Functions that accept or return a position (string index), could return 0-based or 1-based positions. Such functions are labelled with '[WARNING: languages may use 0-based/1-based string indexes]'. Author's Intro: Functions that I would like to see more widely in particular are: StrCount/StrRept (e.g. they are used in algorithms and for counting lines/URLs) StrEquals/StrContains/StrStarts/StrEnds (safer and clearer than alternatives, more convenient than creating a function every time they're needed, and would enable the easier migration of code between programming languages) And languages to have both of: SubStr (pos/length) and StrSlice (pos1/pos2) UFL notes: StrLower/StrUpper format: StrLower(Text, LocaleOrStandard:=unset) format: StrUpper(Text, LocaleOrStandard:=unset) demo: StrLower("ABC Abc abc") ;abc abc abc demo: StrUpper("ABC Abc abc") ;ABC ABC ABC recommendation: one simple standard would only modify chars A-Z/a-z UFL notes: StrTitle [set all words to title case] format: StrTitle(Text, LocaleOrStandard:=unset, Options:=unset) demo: StrTitle("ABC Abc abc") ;Abc Abc Abc recommendation: set all words to title case, some functions simply capitalise the first character recommendation: introduce one or more ISO 'title case' standards recommendation: make available information to match title case in common programs e.g. MS Word/MS Excel recommendation: options could include: only modify words that are lower case recommendation: options could include: words that should not be modified recommendation: options could include: words that should not be forcibly made lower case UFL notes: StrCompare/StrEquals format: StrCompare(Text1, Text2, CaseSen:=unset) [note: returns positive/0/negative] format: StrEquals(Text1, Text2, CaseSen:=unset) demo: StrCompare("abc", "def") ;-1 demo: StrEquals("abc", "def") ;False recommendation: SAFETY: while !StrCompare would be equivalent to StrEquals, for code clarity and code safety, it is worth having both recommendation: it is always worthwhile to have function versions of common operators (e.g. '==') recommendation: StrEquals(a, b, IgnoreCase) beats (a.lowercase == b.lowercase) recommendation: having StrEquals completes the set of StrEquals/StrContains/StrStarts/StrEnds UFL notes: (StrBetween)/(StrBetweenUntil) [between: inclusive to inclusive, until: inclusive to exclusive] format: StrBetween(Needle, Bound1, Bound2, CaseSen:=unset) format: StrBetweenUntil(Needle, Bound1, Bound2, CaseSen:=unset) demo: StrBetween("abc", "a", "abc") ;True demo: StrBetweenUntil("abc", "a", "abc") ;False demo: StrBetweenUntil("abc", "a", "b") ;True recommendation: SAFETY: for safety, it is better if < > <= >= do not compare strings, but instead throw, thus functions are wanted instead UFL notes: Chr [codepoint to character] format: Chr(Number, Options:=unset) demo: Chr(97) ;a recommendation: the default could be to consider codepoints, with an option to consider subunits e.g. UTF-16 2-byte 'chars' UFL notes: Ord [codepoint at start of string] format: Ord(Text, Options:=unset) demo: Ord("abc") ;97 recommendation: the default could be to consider codepoints, with an option to consider subunits e.g. UTF-16 2-byte 'chars' UFL notes: ChrAt/OrdAt [nth character/codepoint of nth character][WARNING: languages may use 0-based/1-based string indexes] format: ChrAt(Text, Pos, Options:=unset) format: OrdAt(Text, Pos, Options:=unset) demo: ChrAt("abc", 2) ;b (1-based position) demo: OrdAt("abc", 2) ;98 (1-based position) recommendation: SAFETY: 1-based positions are safer and more intuitive (but the language may already be using 0-based positions) UFL notes: StrRept [or StrRepeat] format: StrRept(Text, Count) demo: StrRept("abc_", 3) ;abc_abc_abc_ recommendation: 'Rept' rather than 'Repeat', to keep the name short, it can often be used multiple times in one expression UFL notes: StrCount [WARNING: languages may use 0-based/1-based string indexes] format: StrCount(Text, Needle, CaseSen:=unset, Pos:=unset) demo: StrCount("abcabcabc", "a") ;3 UFL notes: StrLen/(StrLenCodepoints) format: StrLen(Text, Options:=unset) demo: StrLen("abc") ;3 recommendation: the default could be to consider codepoints, with an option to consider subunits e.g. UTF-16 2-byte 'chars' UFL notes: StrReplace [replace string with string (no RegEx), all occurrences, there may be an option to replace the first n occurrences][WARNING: languages may use 0-based/1-based string indexes] format: StrReplace(Text, Before, After:="", CaseSen:=unset, &Count:=unset, Limit:=unset, Pos:=unset) demo: StrReplace("abcabcabc", "b", "_",, &Count) ;a_ca_ca_ca_c (Count is 4) demo: StrReplace("abcabcabcabc", "b", "_",, &Count, 1, 7) ;abcabca_cabc (Count is 1) recommendation: if After is omitted, then replace the needle text (Before) with blank strings recommendation: a ByRef Count parameter could return the number of replacements made (alternatively an Options parameter could return [Output, Count] or just Count) recommendation: a Limit parameter could limit how many replacements are made, with no limit by default UFL notes: StrSplit/StrChunk/(StrHatch) [StrSplit: string to array (split by delimiters), StrChunk (or StrSplitLen): string to array (split into chunks of n chars), StrHatch: add a separator every n chars] format: StrSplit(Text, Delim:="", OmitChars:="", MaxParts:=unset) format: StrChunk(Text, Length, Options:=unset) format: StrHatch(Text, Sep, Length:=1, Options:=unset) demo: StrSplit("abc") ;[a,b,c] demo: StrSplit("a,b,c", ",") ;[a,b,c] demo: StrSplit("a|b|c", "|") ;[a,b,c] demo: StrChunk("abcdef", 2) ;[ab,cd,ef] demo: StrHatch("abcdef", "|", 2) ;ab|cd|ef recommendation: StrSplit: if Delim is blank, split into an array of 1-char strings recommendation: if MaxParts is n, return n-1 normal parts, and one 'rest of' part recommendation: Options: for StrChunk/StrHatch, this could start chunking/hatching from the right author's note: for StrHatch: 'Length' then 'Sep' might be a better fit with StrChunk author's note: I coined 'StrHatch', based on the idea of cross-hatching in drawing, adding lines at fixed intervals (but alternative names are welcome) UFL notes: StrJoin [specify separator string, then one or more strings][e.g. StrJoin(vSep, oValues*)] format: StrJoin(Sep, Values*) demo: StrJoin(",", ["a", "b", "c"]) ;a,b,c demo: StrJoin(["=", ","], ["k1", "v1", "k2", "v2"]) ;k1=v1,k2=v2 UFL notes: StrContains/InStr/InStrRev [WARNING: languages may use 0-based/1-based string indexes] format: StrContains(Text, Needle, CaseSen:=unset) format: InStr(Text, Needle, CaseSen:=unset, Pos:=unset, Occ:=unset) format: InStrRev(Text, Needle, CaseSen:=unset, Pos:=unset, Occ:=unset) recommendation: SAFETY: InStr/InStrRev as separate functions simplifies the usage (search left-to-right versus right-to-left) UFL notes: StrStarts/StrEnds [see also: StrEquals/StrContains] format: StrStarts(Text, Needle, CaseSen:=unset) format: StrEnds(Text, Needle, CaseSen:=unset) UFL notes: RegExIndex [find offset of first match, get text of any substrings][WARNING: languages may use 0-based/1-based string indexes] format: RegExIndex(Text, Needle, &Match:=unset, Pos:=unset) UFL notes: (RegExEquals) format: RegExEquals(Text, Needle, &Match:=unset, Pos:=unset) UFL notes: RegExAll [find all matches][WARNING: languages may use 0-based/1-based string indexes] format: RegExAll(Text, Needle, Pos:=unset) UFL notes: RegExReplace format: RegExReplace(Text, Needle, Replacement:="", &Count:=unset, Limit:=unset, Pos:=unset) UFL notes: StrEscape [or RegExEscape][add escape characters to treat all characters literally rather than as metacharacters] format: StrEscape(Text, CharList:="", Options:=unset) recommendation: CharList to determine which characters to escape recommendation: options could allow RegEx escaping using '\Q' and '\E' UFL notes: SubStr [substring using pos/length][WARNING: languages may use 0-based/1-based string indexes] format: SubStr(Text, Pos, Count) UFL notes: (StrSlice) [substring using pos1/pos2][WARNING: languages may use 0-based/1-based string indexes] format: StrSlice(Text, Pos1, Post2) UFL notes: (StrLeft)/(StrRight) format: StrLeft(Text, Count) format: StrRight(Text, Count) recommendation: SAFETY: unlike other slice functions, these handily avoid using 1-based/0-based positions (string indexes) recommendation: if Text is shorther than Count, return the whole string UFL notes: (StrDropLeft)/(StrDropRight) format: StrDropLeft(Text, Count) format: StrDropRight(Text, Count) recommendation: SAFETY: unlike other slice functions, these handily avoid using 1-based/0-based positions (string indexes) recommendation: if Text is shorther than Count, return a blank string UFL notes: (StrSort) [sort string based on a delimiter char] format: Sort(Text, Options, Callback) format: Sort(Text, Callback) author's note: there are various parameter options, including having a separate Delimiter parameter UFL notes: (StrAlphabetize)/(StrReverse)/(StrShuffle) format: StrAlphabetize(Text, CaseSen:=unset) format: StrReverse(Text) format: StrShuffle(Text) UFL notes: Trim/LTrim/RTrim [crop chars from start/end/both] recommendation: handle any characters, not just whitespace characters format: Trim(Text, OmitChars:=" \t") format: LTrim(Text, OmitChars:=" \t") format: RTrim(Text, OmitChars:=" \t") UFL notes: StrDiff/(StrDiffFirst)/(StrDiffLast) [WARNING: languages may use 0-based/1-based string indexes] format: StrDiff(Text1, Text2, CaseSen:=unset) [note: returns the position of the first difference between 2 strings] UFL notes: Format [produce text in a similar way to sprintf (using string interpolation): a format string and parameters] format: Format(FormatStr, Values*) UFL notes: (StrConcat) format: StrConcat(Values*) UFL notes: StrPadLeft/StrPadRight UFL notes: StrSpan/StrCompSpan [span / complementary span e.g. count the leading whitespace chars] format: JEE_StrSpan(Text, NeedleChars) format: JEE_StrCompSpan(Text, NeedleChars) UFL notes: (StrWrap) UFL notes: ChrUnused [ChrUnused(Strings*), return a char not present in Strings*] format: ChrUnused(Values*) recommendation: an Options object could give more granular control author's note: where possible, consider adding functions that reduce the need for a ChrUnused function (e.g. StrChunk) UFL notes: (StrToName) [or StrToFilename] format: StrToName(Title, LocaleOrStandard) author's note: e.g. for a webpage title, what file name would the web browser save it as