String Operations


The length() Method

The string class has a length method. The next program uses length().

// string_b - introduction to strings

string_b()
{
    s = "hello world"
    s.println()
    l = s.length()
    o = "length of: \"" + s + "\" is: " + l.to_string()
    o.println()
}

The output of the program is as follows.

hello world
length of: "hello world" is: 11

From the output it is apparent that the length() method delivers the number of characters in the string (and there is no null-terminator).

The String Indexer

The string class has an indexer. The indexer is a zero-based, readonly indexer. Characters can be read from the string but the string cannot be updated through this indexer. s[0] delivers the first byte in the string - which is 'h'.

// string_d - the indexer

string_d()
{
    s = "hello world"
    s.println()
    b = s[0]
    b.println()
}

The output of the program is shown below.

hello world
104

Equality and Inequality

String equality (==) and inequality operators (!=) are defined. These compare the contents of two strings. For example, the following program uses equality and inequality.

// string_c - equality and inequality of strings

string_c()
{
    a = "hello world"
    b = "goodbye world"
    c = "hello world"

    if a != b
    {
        s = a + " != " + b
        s.println()
    }

    if a == c
    {
        s = a + " == " + c
        s.println()
    }

    if b < a
    {
        s = b + " < " + a
        s.println()
    }
}

The output of the program is as follows.

hello world != goodbye world
hello world == hello world
goodbye world < hello world