Substring

From BR Wiki
Jump to navigation Jump to search
The printable version is no longer supported and may have rendering errors. Please update your browser bookmarks and please use the default browser print function instead.

In BR, a substring of a string is a subset of the symbols in a string, where the order of the elements is preserved.

Therefore, "ball" is a substring of "snowball", but "bow" is not. Even though all the letters in "bow" are also contained in "snowball", they are not in the same order.

In order to extract a substring from its parent string, we must use a start and stop subscripts. The syntax

parent$(start:stop)

denotes "the substring of string parent$ starting at character start and ending at character end"

Below is an example of how subscripts can be used to extract substrings from strings:

00010 dim a$*255, b$*255
00020 let a$ = "from this long string, choose these words"
00030 let b$ = a$(24:41)
00040 print b$

The output of the above example will be:

choose these words

Modify

A BR String may be modified using its subscripts. For example, A$(4:6) uses the substring of A$ beginning with position 4 up to and including position 6; the numbers inside the parentheses could be replaced by any numeric expression. In the following example, line 40 sets element 3 of array Z$ to "XXC":

00010 LET Z$(3) = "ABC"
00020 LET A = 1
00030 LET B = 2
00040 LET Z$(3)(A:B) = "XX"

In the next example, line 40 replaces "BC" with "23" and assigns the value "A23D" to X$:

00030 LET X$ = "ABCD"
00040 LET X$(2:3) = "23"

Note that you the number of characters being replaced does not have to match the number of characters they are being replaced with. Consider the following example:

00010 dim a$*255
00020 let a$ = "beginning end"
00030 let a$(10:10) = " middle " ! here we are replacing one character (a space) with 6 characters (" middle ")
00040 print a$

The result of the example above is

beginning middle end


Insert


Prepend

To prepend string1$ to string2$ means to join string1$ to the beginning of string2$.

To append to the beginning of a string you should use

X$(0:0)="append this to front"

or alternately

X$(1:0)="append this to front"

For example,

00010 dim result$*255 ! dimension long enough to fit the result
00020 let result$ = " and this is the end"
00030 let string_to_prepend$ = "this is the front"
00040 let result$(0:0) = string_to_prepend$
00050 print result$

The output of the program above will be:

this is the front and this is the end


Append

To append string2$ to string1$ means to join string2$ to the end of string1$.

To append to the end of a String you should (for maximum speed of code execution) use

X$(inf:0)="append this to end"

OR

X$(inf:inf)="append this to the end"

Here, inf denotes infinity.

So X$(inf:inf) means "the substring of X$ starting at infinity". This is particularly useful when you don't know how long your string is and do not want to calculate its length.

see also: prepend


Delete