Learn to Program Computers - String Processing


1. How do I program with strings?

When learning to program, strings are one of the most useful data types. They can store any amount of text, including line breaks and tabs, and they can easily be printed, loaded and saved to text files. Strings can be stored as string constants and variables, and can be merged using the plus sign for string concatenation. For example:

  Mystring1 <- "Hello"
  Mystring2 <- Mystring1 + " World"

After this code runs, Mystring2 has the value "Hello World".

2. How long is a string?

Use the Length function (or a ruler). For example:

  Mystring1 <- "I am a string"
  i <- Length(Mystring1)
  // i now equals 13

3. How do I delete from strings?

Use the Strdel function to delete sections of a string. The first argument is the string having sections deleted from it (only the returned string is altered, not the string passed to Strdel), the second argument is the starting index for the deleted text, and the third argument is the number of characters to delete. For example:

  Mystring1 <- "I am a string"
  Mystring2 <- Strdel(Mystring1, 1, 5)
  // Mystring2 now equals "a string"

If the third argument specifies characters beyond the end of the string, only the characters to the end of the string are deleted, and no error occurs.

4. How do I copy sections of a string?

Use Strcopy to extract a substring. For example:

  Mystring1 <- "I am a string"
  Mystring2 <- Strcopy(Mystring1, 1, 4)
  // Mystring2 now equals "I am"

Similarly to Strdel if you specify more characters than are in the string, only the characters to the end of the string are copied, and no error occurs.

Another useful function is Strch which returns the integer value of a single character from a string. Strch is useful for string processing because it is very fast, it does not use any memory allocation and it can also modify characters in the string. If you are used to programming in C/C++ or Pascal, you will be familiar with efficient access to single characters in a string using code such as the following:

  ch = Mystring1[i];
  Mystring[j] = ch;

The equivalent in Ubercode is:

  ch <- Strch(Mystring1, i)
  call Strch(Mystring, j, ch)

Bear in mind that Pascal and Ubercode both use indexes based on 1, and C/C++ uses indexes based on zero.