Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions LEARNING_PATH_ROADMAP.md
Original file line number Diff line number Diff line change
Expand Up @@ -181,7 +181,7 @@ This branch teaches Tcl's value-based collections and functional idioms.
- **Teaches**: The `{*}` expansion operator, passing lists as individual arguments, and avoiding `eval` injection/shimmering bugs.
- **Concept Exercise Idea**: *Command Dispatcher* (new story) — forward dynamically assembled argument lists safely using `{*}`.

### 15. `dictionaries`
### 15. `dictionaries` ✅

- **Prerequisites**: `lists`
- **Teaches**: `dict create`, `get`, `getwithdefault` (Tcl 9), `set`, `unset`, `incr`, `exists`, `keys`, `values`, `for`, `map`, and nested dictionaries.
Expand Down Expand Up @@ -209,7 +209,7 @@ This branch focuses on formatted text, binary protocols, dates and times, and pa
- **Teaches**: `string equal` and `string compare` (`-nocase`, `-length`), string comparison operators in `expr` (`eq`, `ne`, `lt`, `gt`, `le`, `ge`), and `string is` character classes (`alpha`, `digit`, `alnum`, `wordchar`, `space`, `ascii`, `-strict`, `-failindex`).
- **Concept Exercise Idea**: *Identifier Validator* (new story) -- validate character classes, check prefixes, and compare normalized identifiers case-insensitively.

### 19. `substrings`
### 19. `substrings` ✅

- **Prerequisites**: `strings`
- **Teaches**: Substring lookup (`string first`, `string last`), `string replace`, and Tcl 9 `string insert`.
Expand Down
7 changes: 7 additions & 0 deletions concepts/substrings/.meta/config.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"authors": [
"glennj"
],
"contributors": [],
"blurb": "Locate substrings with string first/last, replace ranges with string replace, and insert text with string insert."
}
142 changes: 142 additions & 0 deletions concepts/substrings/about.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,142 @@
# Substrings

Tcl's `string` command includes subcommands for locating exact substrings (`string first`, `string last`), replacing or deleting character ranges (`string replace`), and inserting text at an index (`string insert`).
All of these commands operate on zero-based Unicode codepoint indices and return a new string rather than mutating a variable in place.

## Searching for Substrings (`string first`, `string last`)

Both search commands take a `needle` to look for, a `haystack` to search, and an optional bounding index:

- `string first needle haystack ?startIndex?` searches forward starting at `startIndex` (default `0`) and returns the index of the first character of the earliest match.
- `string last needle haystack ?lastIndex?` searches backward and returns the index of the first character of the latest match whose characters all fall at or before `lastIndex` (default `end`).

When `needle` does not appear within the search bounds, both commands return `-1`.

```tcl
set record "usr:alice:admin:active"

puts [string first ":" $record]
# => 3

puts [string first ":" $record 4]
# => 9

puts [string last ":" $record]
# => 15

puts [string last ":" $record 14]
# => 9
```

### Testing Whether a Substring Exists

When `needle` matches at the very start of `haystack`, `string first` returns `0`; when it is absent, `string first` returns `-1`.
Never treat that return value directly as a boolean, because Tcl treats `0` as false and `-1` as true.
Instead, compare the result explicitly against `0` or `-1` (in `expr`, `>=` returns `1` for true and `0` for false):

```tcl
set line "ERROR: disk full"

puts [expr {[string first "ERROR" $line] >= 0}]
# => 1
```

### Search Edge Cases

- **Empty `needle`**: Searching for `""` always returns `-1`, even when `haystack` is also `""`.
- **`lastIndex` covers the whole match**: In `string last`, the entire `needle` must fit at or before `lastIndex`, not just its starting character.
For example, `[string last "ab" "xxabxx" 2]` returns `-1` because the `'b'` is at index `3`, whereas `[string last "ab" "xxabxx" 3]` returns `2`.
- **Out-of-bounds indices**: A `startIndex` before `0` is clamped to `0`, and a `startIndex` past `end` returns `-1`.
Similarly, a `lastIndex` past `end` is clamped to `end`, and a `lastIndex` before `0` returns `-1`.

## Replacing and Deleting Ranges (`string replace`)

`string replace string first last ?newstring?` returns a copy of `string` with all characters from `first` through `last` (**inclusive**) replaced by `newstring`.
If `newstring` is omitted (or `""`), the specified range is removed:

```tcl
set tag "build-2026-01-alpha"

puts [string replace $tag 6 9 "2027"]
# => build-2027-01-alpha

puts [string replace $tag 13 end]
# => build-2026-01
```

Because strings are immutable, `string replace` does not change `$tag`; assign the return value back with `set` if you want to update the variable.

### Replacement Edge Cases

- **Index clamping**: If `first` is less than `0`, it is clamped to `0`.
If `last` is greater than `end`, it is clamped to `end`.
- **No-op ranges**: If `last < first`, `first > end`, or `last < 0`, `string replace` returns `string` unchanged.

```tcl
puts [string replace "abcdef" -3 1 "X"]
# => Xcdef

puts [string replace "abcdef" 4 2 "X"]
# => abcdef

puts [string replace "abcdef" 10 12 "X"]
# => abcdef
```

## Inserting Text (`string insert`)

Introduced in Tcl 9.0, `string insert string index insertString` returns a copy of `string` with `insertString` placed immediately **before** the character at `index`:

```tcl
set item "report.txt"

puts [string insert $item 0 "2026-"]
# => 2026-report.txt

puts [string insert $item 6 "-final"]
# => report-final.txt
```

### How `end` Differs in `string insert`

In `string index`, `string range`, and `string replace`, `end` refers to the last character (`length - 1`).
In `string insert`, `end` refers to the position **after** the last character (`length`), making it natural to append text:

```tcl
set word "abcd"

puts [string insert $word 3 "X"]
# => abcXd

puts [string insert $word end-1 "X"]
# => abcXd

puts [string insert $word end "X"]
# => abcdX
```

### Insertion Edge Cases

- **Out-of-bounds clamping**: An `index` less than `0` clamps to `0` and prepends `insertString`.
An `index` greater than or equal to the string length clamps to `end` and appends `insertString`.
- **Empty strings**: Inserting into `""` at `0` or `end` returns `insertString`, and inserting `""` returns `string` unchanged.

## Combining Lookup and Splicing

`string first` and `string last` pair naturally with `string range`, `string replace`, and `string insert` for structured text edits (using `if`, covered in `conditionals`, to branch on `-1`):

```tcl
proc swap_extension {filename new_ext} {
set dot [string last "." $filename]
if {$dot == -1} {
return [string insert $filename end ".$new_ext"]
}
return [string replace $filename $dot end ".$new_ext"]
}

puts [swap_extension "archive.tar.gz" "zip"]
# => archive.tar.zip

puts [swap_extension "Makefile" "bak"]
# => Makefile.bak
```
61 changes: 61 additions & 0 deletions concepts/substrings/introduction.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
# Substrings

Tcl provides `string` subcommands to locate substrings by codepoint index and to build modified strings by replacing or inserting text at specific positions.
Because Tcl strings are immutable, these commands return a new string without modifying any variable in place.

## Finding Substrings (`string first`, `string last`)

`string first` and `string last` search for an exact substring (`needle`) inside another string (`haystack`) and return a zero-based index, or `-1` if `needle` is not found:

- `string first needle haystack ?startIndex?` searches forward from `startIndex` (default `0`).
- `string last needle haystack ?lastIndex?` searches backward from `lastIndex` (default `end`) and returns the starting index of the last complete match.

```tcl
set path "/var/log/app/server.log"

puts [string first "/" $path]
# => 0

puts [string first "/" $path 1]
# => 4

puts [string last "/" $path]
# => 12

puts [string first ".tmp" $path]
# => -1
```

## Replacing Ranges (`string replace`)

`string replace string first last ?newstring?` returns a new string with the **inclusive** range from `first` through `last` replaced by `newstring`.
If you omit `newstring`, Tcl deletes the characters in that range:

```tcl
set version "release-v1-beta"

puts [string replace $version 8 9 "v2"] ;# replaces "v1"
# => release-v2-beta

puts [string replace $version 10 end] ;# deletes "-beta"
# => release-v1
```

## Inserting Text (`string insert`)

Introduced in Tcl 9.0, `string insert string index insertString` returns a new string with `insertString` inserted immediately **before** `index`:

```tcl
set host "example.com"

puts [string insert $host 0 "api."]
# => api.example.com

puts [string insert $host end ":8080"]
# => example.com:8080

puts [string insert "v10" 2 "."]
# => v1.0
```

Notice that in `string insert`, `end` refers to the position **after** the last character, so `string insert $str end $suffix` appends `$suffix` to the end of `$str`.
6 changes: 6 additions & 0 deletions concepts/substrings/links.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
[
{
"url": "https://www.tcl-lang.org/man/tcl9.0/TclCmd/string.html",
"description": "Official Tcl 9.0 manual page for the string command, covering string first, string last, string replace, and string insert."
}
]
17 changes: 17 additions & 0 deletions config.json
Original file line number Diff line number Diff line change
Expand Up @@ -202,6 +202,18 @@
"procedures"
],
"status": "wip"
},
{
"slug": "uri-inspector",
"name": "URI Inspector",
"uuid": "c03d337c-5bce-4b0c-b9c3-ac0bf8de6a75",
"concepts": [
"substrings"
],
"prerequisites": [
"strings"
],
"status": "wip"
}
],
"practice": [
Expand Down Expand Up @@ -1992,6 +2004,11 @@
"uuid": "e84301ef-e4b3-4197-bc3b-ba7839a426cb",
"slug": "error-handling",
"name": "Error Handling"
},
{
"uuid": "209a2fbe-be22-4d8c-aeb7-d9c363b56a18",
"slug": "substrings",
"name": "Substrings"
}
],
"key_features": [
Expand Down
35 changes: 35 additions & 0 deletions exercises/concept/uri-inspector/.docs/hints.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
# Hints

## General

- All `string` subcommands return a new string without mutating variables in place.
- Remember that `string first` and `string last` return `-1` when the substring is not found, and `0` when it matches at the very start of the string.
- See the [Tcl `string` manual page][tcl-string] for full syntax and edge-case details.

## 1. Locate the scheme separator

- Use `string first` with `"://"` as the needle and `$uri` as the haystack.

## 2. Find a delimiter from a starting offset

- Pass the starting index as the optional fourth argument to `string first` (`string first needle haystack startIndex`).

## 3. Find the last slash within a bound

- Use `string last` with `"/"` as the needle, `$uri` as the haystack, and `$lastIndex` as the upper bound.

## 4. Replace a span in a URI

- Pass all four arguments to `string replace` (`string replace str first last newstring`).
- Both `first` and `last` are inclusive, and `end`-relative indices work automatically.

## 5. Remove a span from a URI

- Omit the replacement argument when calling `string replace` (`string replace str first last`).

## 6. Insert a fragment at an offset

- Use Tcl 9's `string insert` (`string insert str index insertString`).
- In `string insert`, `end` refers to the position after the last character, so passing `end` appends the inserted text.

[tcl-string]: https://www.tcl-lang.org/man/tcl9.0/TclCmd/string.html
77 changes: 77 additions & 0 deletions exercises/concept/uri-inspector/.docs/instructions.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
# Instructions

You are building a lightweight URI inspection and editing toolkit for an internal proxy service.
Rather than pulling in a full URL parser, the proxy locates delimiters by codepoint index and splices segments directly.

Implement six procedures to search, replace, remove, and insert URI fragments.

## 1. Locate the scheme separator

Implement `schemeSeparatorIndex`, which takes a `uri` string and returns the zero-based index of the `"://"` scheme separator, or `-1` if it is not present.

```tcl
schemeSeparatorIndex "https://example.com/api"
# => 5

schemeSeparatorIndex "/relative/path"
# => -1
```

## 2. Find a delimiter from a starting offset

Implement `findDelimiterFrom`, which takes `uri`, `delimiter`, and `startIndex`.
It returns the zero-based index of the first occurrence of `delimiter` in `uri` at or after `startIndex`, or `-1` if none is found.

```tcl
findDelimiterFrom "https://example.com/api/v1" "/" 8
# => 19

findDelimiterFrom "https://example.com/api/v1" "?" 0
# => -1
```

## 3. Find the last slash within a bound

Implement `lastSlashAtOrBefore`, which takes `uri` and `lastIndex` (which may be an integer or an `end`-relative index).
It returns the zero-based index of the last `"/"` in `uri` at or before `lastIndex`, or `-1` if no `"/"` appears within that bound.

```tcl
lastSlashAtOrBefore "https://example.com/api/v1" end
# => 23

lastSlashAtOrBefore "https://example.com/api/v1" 22
# => 19
```

## 4. Replace a span in a URI

Implement `replaceSpan`, which takes `uri`, `first`, `last`, and `replacement`.
It returns a new string with the inclusive range from `first` through `last` (including `end`-relative indices) replaced by `replacement`.

```tcl
replaceSpan "https://example.com/v1/users" 20 21 "v2"
# => https://example.com/v2/users
```

## 5. Remove a span from a URI

Implement `deleteSpan`, which takes `uri`, `first`, and `last`.
It returns a new string with the inclusive range from `first` through `last` removed.

```tcl
deleteSpan "https://example.com/v1/users?debug=1" 28 end
# => https://example.com/v1/users
```

## 6. Insert a fragment at an offset

Implement `insertAt`, which takes `uri`, `index`, and `fragment`.
It returns a new string with `fragment` inserted immediately before `index` (supporting `0` to prepend, `end` to append, and `end-N` or integer offsets).

```tcl
insertAt "example.com/api" 0 "https://"
# => https://example.com/api

insertAt "https://example.com/api" end "?v=2"
# => https://example.com/api?v=2
```
Loading
Loading