String Manipulation
Strings are pieces of text that may be displayed in Textfields, in Math Edit
Windows, and in Graph2D windows as labels. They are entered to the system in
the form:
"This is a string" That is, they are surrounded by double quotes.
A string is represented in the system as an atomic symbol, just as a variable
is. The difference between strings and variables is that strings admit spaces
and other special characters, and that strings are case-sensitive. In fact, if
you create a string that consists only of uppercase characters or underscores,
with no lower-case characters, spaces, or special characters (for example:
"THIS" ) it will be interpreted by the system as the variable: this. Thus, whenever you create a string, it should have at least one space,
lower-case character, or special character (see below) to distinguish it from a
variable.
Strings evaluate to themselves in the same way that variables do. Thus, you
cannot assign a value to a string. You may, however, give strings properties
using Putproperty.
The system will therefore never complain that it doesn't know the "value" of a
string.
Special Characters
Unlike variable names, strings may contain special characters, such as:
:,!, @, #, $, %,(,),[,],{,},\ ., and so on. Thus for example, to create a string filename:
You may not, however, insert ', " (single or double quote) or ; (semicolon) in a string.
c:\mathwrit\myvoice.wav
you simply type
make address "c:\mathwrit\myvoice.wav"
There are 3 ways to introduce new strings to the system:
- In text entry, between double quotes
Make newstring "This is a string"
- With the Textstring function, from a Textfield
Make newstring Textstring("Myfield");
- Using the Pack function to "pack" a list of atoms into a string
Make newstring Pack(list( "Myfile", ".bmp"));
Make newstring Pack(list( a,b,c,4));
The dual of the Pack
function is the Explode
Function that returns the list of characters in a string:
print explode("this")
causes (T H I S) to be printed.
These last two ways lead to a variety of string manipulation programs:
- Concatenating strings:
The following function may be used to concatenate strings:
make concat(st s1, st s2) pack(list(s1,s2));
Then the result of
concat( "Myfile", ".bmp")
will be "Myfile.bmp"
- Checking strings for characters:
make checkinstring(ex ch, st target) member(ch, explode(target));
- Reversing Strings:
make function backword of type st (st str) pack(reverse(explode(str)))
-
Then backword("hello") yields "olleh"
If the Pack function produces something that looks like a decimal number, then
it is a decimal number, and not a string.
print 123 + backword(123) yields 444