Welcome, guest | Sign In | My Account | Store | Cart

The split command splits a string based on each character that is in the splitString. This version handles the splitString as a combined string, splitting the string into constituent parts.

Tcl, 15 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
# mcsplit --
#
#   Splits a string based using another string
#
# Arguments:
#   str       string to split into pieces
#   splitStr  substring
#   mc        magic character that must not exist in the orignal string.
#             Defaults to the NULL character.  Must be a single character.
# Results:
#   Returns a list of strings
#
proc mcsplit "str splitStr {mc {\x00}}" {
    return [split [string map [list $splitStr $mc] $str] $mc]
}

This one-line multi-character split is simple and efficient. The splitStr is mapped into the single magic character which can then be passed to split for splitting the string. Be careful to make sure your string does not have NULLs, or to use a different magic character. Perhaps an undefined Unicode character would also be a good default magic character.

Created by Jeff Hobbs on Mon, 10 Sep 2001 (MIT)
Tcl recipes (162)
Jeff Hobbs's recipes (16)

Required Modules

  • (none specified)

Other Information and Tasks