Pure Programmer
Blue Matrix


Cluster Map

Strings

L1

This page is under construction. Please come back later.

At their heart, a string is simply a sequence of characters. Characters, in turn, are encoded as integers using encoding schemes such as [[ASCII]], [[ISO-Latin-1]] or [[Unicode]]. So a string is simply a sequence of integers. Languages like FORTRAN or C that don't support strings as a fundamental type, actually treat strings as a sequence of integers. Modern programming languages support strings as a fundamental data type which make them much easier to use and manipulate.

Strings are particularly useful when conveying information to the user in contrast to being useful for computation like integers or floating point values. While strings are typically implemented as an array/list of the more basic character type, modern languages provide a string data type that encapsulates the characters of a string and provide functionality for working with strings. When using strings in our programs there are two types of strings: [[literal]] strings and string variables.

Variables and Literals

String literals are string values that are directly written in the program itself. String literals only represent the one string as it is typed into the code. String literals are enclosed in double quotes or single quotes. String literals can be used any place a string is required.

"Hello, world!"
"My name is: "
'Four score and seven years ago...'
'z'

Example String Literals

String variables are like any other variable. This means that string variables must be declared before they can be used and must follow the variable naming rules discussed in the variables section. that is they can be set and reset to different values at will. Unlike variables of the primitive types such as boolean, integer and floating point, string variables represent an entire string of characters. String variables can be set using string literals or other string variables.

Concatenation

One of the most basic operations we can perform on strings is called concatenation. Concatenation takes two strings and forms a new one by appending the second string on to the end of the first string. Using concatenation we can build up a complex string from small strings. In JavaScript the concatenation operator is the + (plus) symbol.

Strings1.js
#!/usr/bin/env node;
/******************************************************************************
 * This program demonstrates string concatenation.
 * 
 * Copyright © 2020 Richard Lesh.  All rights reserved.
 *****************************************************************************/

const main = async () => {
	const a = "one";
	const b = "two";
	const c = "three";
	let d = a + b + c;
	console.log(d);
	d = a + "\t" + b + "\n" + c;
	console.log(d);
}
main().catch( e => { console.error(e) } );
Output
$ node Strings1.js onetwothree one two three

Operations on Strings

JavaScript supports a number of operations on strings. The most often used is determining the length of a string. [an error occurred while processing this directive] Counting the characters in a string is accomplished using the length() method. Some of the other string operations available are summarized in the following table.

String Operations
Fixed PointScientific Notation
00e0
3.14153.1415e0
Strings2.js
#!/usr/bin/env node;
/******************************************************************************
 * This program demonstrates basic string functions.
 * 
 * Copyright © 2020 Richard Lesh.  All rights reserved.
 *****************************************************************************/

const Utils = require('./Utils');

const main = async () => {
	const alphabet = "abcdefghijklmnopqrstuvwxyzabc";
	const greekAlphabet = "αβγδεζηθικλμνξοπρσςτυφχψωαβγ";
	const emoji = "😃😇🥰🤪🤑😴🤒🥵🥶🤯🥳😎😥😱😡🤬💀👽🤖😺🙈🙉🙊😃😇🥰";

	console.log("Length: " + Utils.cpLength(alphabet));
	console.log("charAt(17): " + Utils.uniAt(alphabet, 17));
	console.log("codePointAt(17): " + Utils.cpAt(alphabet, 17));
	console.log("substr(23, 26): " + Utils.cpSubstr(alphabet, 23, 3));
	console.log("prefix(6): " + Utils.cpSubstr(alphabet, 0, 6));
	console.log("right_tail(6): " + Utils.cpSubstr(alphabet, 6));
	console.log("suffix(6): " + Utils.cpSubstr(alphabet, Utils.cpLength(alphabet) - 6));
	console.log("find(\'def\'): " + Utils.cpIndexOf(alphabet, "def"));
	console.log("find(\'def\') is not found: " + (Utils.cpIndexOf(alphabet, "def") === -1));
	console.log("find(\'bug\'): " + Utils.cpIndexOf(alphabet, "bug"));
	console.log("find(\'bug\') is not found: " + (Utils.cpIndexOf(alphabet, "bug") === -1));
	console.log("rfind(\'abc\'): " + Utils.cpLastIndexOf(alphabet, "abc"));
	console.log("rfind(\'abc\') is not found: " + (Utils.cpLastIndexOf(alphabet, "abc") === -1));
	console.log("rfind(\'bug\'): " + Utils.cpLastIndexOf(alphabet, "bug"));
	console.log("rfind(\'bug\') is not found: " + (Utils.cpLastIndexOf(alphabet, "bug") === -1));

	console.log("Length: " + Utils.cpLength(greekAlphabet));
	console.log("charAt(17): " + Utils.uniAt(greekAlphabet, 17));
	console.log("codePointAt(17): " + Utils.cpAt(greekAlphabet, 17));
	console.log("substr(23, 26): " + Utils.cpSubstr(greekAlphabet, 23, 3));
	console.log("prefix(6): " + Utils.cpSubstr(greekAlphabet, 0, 6));
	console.log("right_tail(6): " + Utils.cpSubstr(greekAlphabet, 6));
	console.log("suffix(6): " + Utils.cpSubstr(greekAlphabet, Utils.cpLength(greekAlphabet) - 6));
	console.log("find(\'δεζ\'): " + Utils.cpIndexOf(greekAlphabet, "δεζ"));
	console.log("find(\'δεζ\') is not found: " + (Utils.cpIndexOf(greekAlphabet, "δεζ") === -1));
	console.log("find(\'bug\'): " + Utils.cpIndexOf(greekAlphabet, "bug"));
	console.log("find(\'bug\') is not found: " + (Utils.cpIndexOf(greekAlphabet, "bug") === -1));
	console.log("rfind(\'αβγ\'): " + Utils.cpLastIndexOf(greekAlphabet, "αβγ"));
	console.log("rfind(\'αβγ\') is not found: " + (Utils.cpLastIndexOf(greekAlphabet, "αβγ") === -1));
	console.log("rfind(\'bug\'): " + Utils.cpLastIndexOf(greekAlphabet, "bug"));
	console.log("rfind(\'bug\') is not found: " + (Utils.cpLastIndexOf(greekAlphabet, "bug") === -1));

/******************************************************************************
 * Because strings are represented using UTF-16 it takes two characters to
 * represent one codepoint for these emoji.  So lengths and positions are twice
 * what we normally would expect when dealing with Unicode characters.  So the
 * standard string functions basically only work correctly with chraracters from
 * the BMP.  Use the functions from Utils module to work correctly with all 
 * Unicode characters.
 *****************************************************************************/
	console.log("Length: " + Utils.cpLength(emoji));
	console.log("charAt(16): " + Utils.uniAt(emoji, 16));
	console.log("codePointAt(16): " + Utils.cpAt(emoji, 16));
	console.log("substr(20, 24): " + Utils.cpSubstr(emoji, 20, 4));
	console.log("prefix(6): " + Utils.cpSubstr(emoji, 0, 6));
	console.log("right_tail(6): " + Utils.cpSubstr(emoji, 6));
	console.log("suffix(6): " + Utils.cpSubstr(emoji, Utils.cpLength(emoji) - 6));
	console.log("find(\'😱😡🤬\'): " + Utils.cpIndexOf(emoji, "😱😡🤬"));
	console.log("find(\'😱😡🤬\') is not found: " + (Utils.cpIndexOf(emoji, "😱😡🤬") === -1));
	console.log("find(\'bug\'): " + Utils.cpIndexOf(emoji, "bug"));
	console.log("find(\'bug\') is not found: " + (Utils.cpIndexOf(emoji, "bug") === -1));
	console.log("rfind(\'😃😇🥰\'): " + Utils.cpLastIndexOf(emoji, "😃😇🥰"));
	console.log("rfind(\'😃😇🥰\') is not found: " + (Utils.cpLastIndexOf(emoji, "😃😇🥰") === -1));
	console.log("rfind(\'bug\'): " + Utils.cpLastIndexOf(emoji, "bug"));
	console.log("rfind(\'bug\') is not found: " + (Utils.cpLastIndexOf(emoji, "bug") === -1));
}
main().catch( e => { console.error(e) } );
Output
$ node Strings2.js Length: 29 charAt(17): r codePointAt(17): 114 substr(23, 26): xyz prefix(6): abcdef right_tail(6): ghijklmnopqrstuvwxyzabc suffix(6): xyzabc find('def'): 3 find('def') is not found: false find('bug'): -1 find('bug') is not found: true rfind('abc'): 26 rfind('abc') is not found: false rfind('bug'): -1 rfind('bug') is not found: true Length: 28 charAt(17): σ codePointAt(17): 963 substr(23, 26): ψωα prefix(6): αβγδεζ right_tail(6): ηθικλμνξοπρσςτυφχψωαβγ suffix(6): χψωαβγ find('δεζ'): 3 find('δεζ') is not found: false find('bug'): -1 find('bug') is not found: true rfind('αβγ'): 25 rfind('αβγ') is not found: false rfind('bug'): -1 rfind('bug') is not found: true Length: 26 charAt(16): 💀 codePointAt(16): 128128 substr(20, 24): 🙈🙉🙊😃 prefix(6): 😃😇🥰🤪🤑😴 right_tail(6): 🤒🥵🥶🤯🥳😎😥😱😡🤬💀👽🤖😺🙈🙉🙊😃😇🥰 suffix(6): 🙈🙉🙊😃😇🥰 find('😱😡🤬'): 13 find('😱😡🤬') is not found: false find('bug'): -1 find('bug') is not found: true rfind('😃😇🥰'): 23 rfind('😃😇🥰') is not found: false rfind('bug'): -1 rfind('bug') is not found: true

Comparing Strings

Like numeric types, string types are comparable. This means that we can order strings and determine which ones are lower and which ones are higher in that ordering. Strings are ordered using [[Lexicographical Order]] also know as Alphabetic or Dictionary Order. This is done by comparing the first characters of the two strings to determine which string is lower and which is higher. If the first characters are the same, we move on to the second character in each string and so on until a difference is found. Shorter strings always compare lower than a longer string that has the lower string as its prefix. Like numeric types, we have six comparison operators that allow us to determine how two strings compare lexicographically.

String Comparison Operators
OperatorMeaning
==equal to
!=not equal to
<less than
<=less than or equal
>greater than
>=greater than or equal
Strings3.js
#!/usr/bin/env node;
/******************************************************************************
 * This program demonstrates string comparisons.
 * 
 * Copyright © 2020 Richard Lesh.  All rights reserved.
 *****************************************************************************/

const main = async () => {
	const color1 = "Blue";
	const color2 = "Red";
	let result;

	console.log("compare(color1, color2): " + color1.localeCompare(color2));
	result = color1 < color2;
	console.log("color1 < color2: " + result);
	result = color1 > color2;
	console.log("color1 > color2: " + result);
	result = color1 === color2;
	console.log("color1 == color2: " + result);
	result = color1 !== color2;
	console.log("color1 != color2: " + result);
}
main().catch( e => { console.error(e) } );
Output
$ node Strings3.js compare(color1, color2): -1 color1 < color2: true color1 > color2: false color1 == color2: false color1 != color2: true

Character Types

Often it is necessary to determine what class an individual character belongs. Character classes such as alphabetic, numeric, whitespace, control and punctuation are common classes of characters in which we would be interested. The following table illustrates how we would determine the class of a character.

Strings4.js
#!/usr/bin/env node;
/******************************************************************************
 * This program illustrates some of the string functions in Utils
 * 
 * Copyright © 2020 Richard Lesh.  All rights reserved.
 *****************************************************************************/

const Utils = require('./Utils');

const ltrstr = "   Spaces to the left";
const rtrstr = "Spaces to the right  ";
const trimstr = "   Spaces at each end   ";
const blank = "  \t\n  ";
const lowerstr = "This String is Lowercase";
const upperstr = "This String is Uppercase";

const main = async () => {
	console.log("|" + Utils.ltrim(ltrstr) + "|");
	console.log("|" + Utils.rtrim(rtrstr) + "|");
	console.log("|" + Utils.trim(trimstr) + "|");
	console.log("|" + Utils.trim(blank) + "|");
	console.log("|" + lowerstr.toLowerCase() + "|");
	console.log("|" + upperstr.toUpperCase() + "|");
}
main().catch( e => { console.error(e) } );

Output
$ node Strings4.js |Spaces to the left| |Spaces to the right| |Spaces at each end| || |this string is lowercase| |THIS STRING IS UPPERCASE|
Character Classification
FunctionDescription
isalnum(c)Check if character is alphanumeric.
isalpha(c)Check if character is alphabetic.
isblank(c)Check if character is blank.
iscntrl(c)Check if character is a control character.
isdigit(c)Check if character is decimal digit.
isgraph(c)Check if character has graphical representation.
islower(c)Check if character is lowercase letter.
isprint(c)Check if character is printable.
ispunct(c)Check if character is a punctuation character.
isspace(c)Check if character is a white-space.
isupper(c)Check if character is uppercase letter.
isxdigit(c)Check if character is hexadecimal digit.

Character Conversion
FunctionDescription
tolower(c)Returns lowercase version of the character.
toupper(c)Returns uppercase version of the character.
javascript

Questions

Projects

More ★'s indicate higher difficulty level.

References