Next: , Previous: , Up: strings   [Index]

### 25.16 Replicate and rotate

Function: %xsubstring from to str start past
Macro: xsubstring S from to

Extended substring procedure replicating the selected substring “up and down” index space, in both the positive and negative directions.

The call:

```(%xsubstring from to "abcdefg" 3 6)
```

selects the substring `"def"` and defines the conceptual bidirectionally–infinite string:

```...  e  f  d  e  f  d  e  f  d  e  f ...
... -5 -4 -3 -2 -1  0 +1 +2 +3 +4 +5 ...
^
```

that is `def` repeated in both directions. `%xsubstring` returns the substring of this string beginning at index from, and ending at to.

We can use this function to perform a variety of tasks:

• To replicate a string:
```(xsubstring "abc" 0 7) ⇒ "abcabca"
```
• To rotate a string left:
```(xsubstring "abcdef" 1  7) ⇒ "bcdefa"
(xsubstring "abcdef" 2  8) ⇒ "cdefab"
(xsubstring "abcdef" 3  9) ⇒ "defabc"
(xsubstring "abcdef" 4 10) ⇒ "efabcd"
(xsubstring "abcdef" 5 11) ⇒ "fabcde"
```
• To rotate a string right:
```(xsubstring "abcdef" -1 5) ⇒ "fabcde"
(xsubstring "abcdef" -2 4) ⇒ "efabcd"
(xsubstring "abcdef" -3 3) ⇒ "defabc"
(xsubstring "abcdef" -4 2) ⇒ "cdefab"
(xsubstring "abcdef" -5 1) ⇒ "bcdefa"
```

Note that:

• The from/to indices give a half–open range; the characters from index from up to, but not including, index to.
• The from/to indices are not in terms of the index space for string str. They are in terms of the replicated index space of the substring defined by str, start, and past.

It is an error if start equals past.

Function: xstring-xcopy! from to target target-start source source-start source-past
Macro: string-xcopy! target-S source-S from to

Exactly the same as `%xsubstring`, but the extracted text is written into the selected substring of target.

This operation is not defined if `(eq? target start)`; we cannot copy a string on top of itself.

Next: , Previous: , Up: strings   [Index]