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: ${name}"
'Four score and seven years ago...'
'z'

Example String Literals

String literals enclosed in double quotes allow for variable interpolation whereas string literals enclosed in single quotes do not. By placing a variable inside a string literal using the ${varname} syntax, Perl will substitute into the string the current value of the variable.

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 Perl the concatenation operator is the . (period) symbol.

Strings1.pl
#!/usr/bin/env perl
use utf8;
###############################################################################
# This program demonstrates string concatenation.
# 
# Copyright © 2020 Richard Lesh.  All rights reserved.
###############################################################################

use strict;
use warnings;

MAIN:
{
	my $a = "one";
	my $b = "two";
	my $c = "three";
	my $d = $a . $b . $c;
	print $d, "\n";
	$d = $a . "\t" . $b . "\n" . $c;
	print $d, "\n";
}

Output
$ perl Strings1.pl onetwothree one two three

Operations on Strings

Perl 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.pl
#!/usr/bin/env perl
use utf8;
###############################################################################
# This program demonstrates basic string functions.
# 
# Copyright © 2020 Richard Lesh.  All rights reserved.
###############################################################################

use strict;
use warnings;

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

	print "Length: ", length($alphabet), "\n";
	print "charAt(17): ", substr($alphabet, 17, 1), "\n";
	print "codePointAt(17): ", ord(substr($alphabet, 17, 1)), "\n";
	print "substr(23, 26): ", substr($alphabet, 23, 3), "\n";
	print "prefix(6): ", substr($alphabet, 0, 6), "\n";
	print "right_tail(6): ", substr($alphabet, 6), "\n";
	print "suffix(6): ", substr($alphabet, -6), "\n";
	print "find(\'def\'): ", index($alphabet, "def"), "\n";
	print "find(\'def\') is not found: ", (index($alphabet, "def") == -1), "\n";
	print "find(\'bug\'): ", index($alphabet, "bug"), "\n";
	print "find(\'bug\') is not found: ", (index($alphabet, "bug") == -1), "\n";
	print "rfind(\'abc\'): ", rindex($alphabet, "abc"), "\n";
	print "rfind(\'abc\') is not found: ", (rindex($alphabet, "abc") == -1), "\n";
	print "rfind(\'bug\'): ", rindex($alphabet, "bug"), "\n";
	print "rfind(\'bug\') is not found: ", (rindex($alphabet, "bug") == -1), "\n";

	print "Length: ", length($greekAlphabet), "\n";
	print "charAt(17): ", substr($greekAlphabet, 17, 1), "\n";
	print "codePointAt(17): ", ord(substr($greekAlphabet, 17, 1)), "\n";
	print "substr(23, 26): ", substr($greekAlphabet, 23, 3), "\n";
	print "prefix(6): ", substr($greekAlphabet, 0, 6), "\n";
	print "right_tail(6): ", substr($greekAlphabet, 6), "\n";
	print "suffix(6): ", substr($greekAlphabet, -6), "\n";
	print "find(\'δεζ\'): ", index($greekAlphabet, "δεζ"), "\n";
	print "find(\'δεζ\') is not found: ", (index($greekAlphabet, "δεζ") == -1), "\n";
	print "find(\'bug\'): ", index($greekAlphabet, "bug"), "\n";
	print "find(\'bug\') is not found: ", (index($greekAlphabet, "bug") == -1), "\n";
	print "rfind(\'αβγ\'): ", rindex($greekAlphabet, "αβγ"), "\n";
	print "rfind(\'αβγ\') is not found: ", (rindex($greekAlphabet, "αβγ") == -1), "\n";
	print "rfind(\'bug\'): ", rindex($greekAlphabet, "bug"), "\n";
	print "rfind(\'bug\') is not found: ", (rindex($greekAlphabet, "bug") == -1), "\n";

	print "Length: ", length($emoji), "\n";
	print "charAt(16): ", substr($emoji, 16, 1), "\n";
	print "codePointAt(16): ", ord(substr($emoji, 16, 1)), "\n";
	print "substr(20, 24): ", substr($emoji, 20, 4), "\n";
	print "prefix(6): ", substr($emoji, 0, 6), "\n";
	print "right_tail(6): ", substr($emoji, 6), "\n";
	print "suffix(6): ", substr($emoji, -6), "\n";
	print "find(\'😱😡🤬\'): ", index($emoji, "😱😡🤬"), "\n";
	print "find(\'😱😡🤬\') is not found: ", (index($emoji, "😱😡🤬") == -1), "\n";
	print "find(\'bug\'): ", index($emoji, "bug"), "\n";
	print "find(\'bug\') is not found: ", (index($emoji, "bug") == -1), "\n";
	print "rfind(\'😃😇🥰\'): ", rindex($emoji, "😃😇🥰"), "\n";
	print "rfind(\'😃😇🥰\') is not found: ", (rindex($emoji, "😃😇🥰") == -1), "\n";
	print "rfind(\'bug\'): ", rindex($emoji, "bug"), "\n";
	print "rfind(\'bug\') is not found: ", (rindex($emoji, "bug") == -1), "\n";
}

Output
$ perl Strings2.pl 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: find('bug'): -1 find('bug') is not found: 1 rfind('abc'): 26 rfind('abc') is not found: rfind('bug'): -1 rfind('bug') is not found: 1 Length: 28 charAt(17): σ codePointAt(17): 963 substr(23, 26): ψωα prefix(6): αβγδεζ right_tail(6): ηθικλμνξοπρσςτυφχψωαβγ suffix(6): χψωαβγ find('δεζ'): 3 find('δεζ') is not found: find('bug'): -1 find('bug') is not found: 1 rfind('αβγ'): 25 rfind('αβγ') is not found: rfind('bug'): -1 rfind('bug') is not found: 1 Length: 26 charAt(16): 💀 codePointAt(16): 128128 substr(20, 24): 🙈🙉🙊😃 prefix(6): 😃😇🥰🤪🤑😴 right_tail(6): 🤒🥵🥶🤯🥳😎😥😱😡🤬💀👽🤖😺🙈🙉🙊😃😇🥰 suffix(6): 🙈🙉🙊😃😇🥰 find('😱😡🤬'): 13 find('😱😡🤬') is not found: find('bug'): -1 find('bug') is not found: 1 rfind('😃😇🥰'): 23 rfind('😃😇🥰') is not found: rfind('bug'): -1 rfind('bug') is not found: 1

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. Additionally we have the comparison operator that returns a negative value if the first string is less than the second, a positive value if the first string is greater than the second, and 0 if the two strings are equal.

String Comparison Operators
OperatorMeaning
eqequal to
nenot equal to
ltless than
leless than or equal
gtgreater than
gegreater than or equal
cmpcompare
Strings3.pl
#!/usr/bin/env perl
use utf8;
###############################################################################
# This program demonstrates string comparisons.
# 
# Copyright © 2020 Richard Lesh.  All rights reserved.
###############################################################################

use strict;
use warnings;

MAIN:
{
	binmode(STDOUT, ":utf8");
	binmode(STDERR, ":utf8");
	binmode(STDIN, ":utf8");
	my $color1 = "Blue";
	my $color2 = "Red";
	my $result;

	print "compare(color1, color2): ", $color1 cmp $color2, "\n";
	$result = $color1 lt $color2;
	print "color1 < color2: ", $result, "\n";
	$result = $color1 gt $color2;
	print "color1 > color2: ", $result, "\n";
	$result = $color1 eq $color2;
	print "color1 == color2: ", $result, "\n";
	$result = $color1 ne $color2;
	print "color1 != color2: ", $result, "\n";
}

Output
$ perl Strings3.pl compare(color1, color2): -1 color1 < color2: 1 color1 > color2: color1 == color2: color1 != color2: 1

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.pl
#!/usr/bin/env perl
use utf8;
###############################################################################
# This program illustrates some of the string functions in Utils
# 
# Copyright © 2020 Richard Lesh.  All rights reserved.
###############################################################################

use Utils;
use strict;
use warnings;

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

MAIN:
{
	print "|", Utils::ltrim($ltrstr), "|\n";
	print "|", Utils::rtrim($rtrstr), "|\n";
	print "|", Utils::trim($trimstr), "|\n";
	print "|", Utils::trim($blank), "|\n";
	print "|", lc($lowerstr), "|\n";
	print "|", uc($upperstr), "|\n";
}


Output
$ perl Strings4.pl |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.
perl

Questions

Projects

More ★'s indicate higher difficulty level.

References