### 5.5 Manipulating Strings

Octave supports a wide range of functions for manipulating strings. Since a string is just a matrix, simple manipulations can be accomplished using standard operators. The following example shows how to replace all blank characters with underscores.

         quote = ...
           "First things first, but not necessarily in that order";
         quote( quote == " " ) = "_"
         ⇒ quote =
             First_things_first,_but_not_necessarily_in_that_order

For more complex manipulations, such as searching, replacing, and general regular expressions, the following functions come with Octave.

— Function File: deblank (s)

> Remove trailing whitespace and nulls from s. If s is a matrix, deblank trims each row to the length of longest string. If s is a cell array of strings, operate recursively on each string element.

> Examples:

>               deblank ("    abc  ")
>                    ⇒  "    abc"

>               deblank ([" abc   "; "   def   "])
>                    ⇒  [" abc  " ; "   def"]

> See also: strtrim.

— Function File: strtrim (s)

> Remove leading and trailing whitespace from s. If s is a matrix, strtrim trims each row to the length of longest string. If s is a cell array of strings, operate recursively on each string element. For example:

>               strtrim ("    abc  ")
>                    ⇒  "abc"

>               strtrim ([" abc   "; "   def   "])
>                    ⇒  ["abc  "  ; "  def"]

> See also: deblank.

— Function File: strtrunc (s, n)

> Truncate the character string s to length n. If s is a character matrix, then the number of columns is adjusted. If s is a cell array of strings, then the operation is performed on each cell element and the new cell array is returned.

— Function File: findstr (s, t)
— Function File: findstr (s, t, overlap)

> Return the vector of all positions in the longer of the two strings s and t where an occurrence of the shorter of the two starts. If the optional argument overlap is true, the returned vector can include overlapping positions (this is the default). For example:

>               findstr ("ababab", "a")
>                    ⇒ [1, 3, 5];
>               findstr ("abababa", "aba", 0)
>                    ⇒ [1, 5]

> Caution: `findstr` is scheduled for deprecation. Use `strfind` in all new code.

> See also: strfind, strmatch, strcmp, strncmp, strcmpi, strncmpi, find.

— Function File: idx = strchr (str, chars)
— Function File: idx = strchr (str, chars, n)
— Function File: idx = strchr (str, chars, n, direction)
— Function File: [i, j] = strchr (...)

> Search for the string str for occurrences of characters from the set chars. The return value(s), as well as the n and direction arguments behave identically as in `find`.

> This will be faster than using regexp in most cases.

> See also: find.

— Function File: index (s, t)
— Function File: index (s, t, direction)

> Return the position of the first occurrence of the string t in the string s, or 0 if no occurrence is found. s may also be a string array or cell array of strings.

> For example:

>               index ("Teststring", "t")
>                    ⇒ 4

> If direction is ‘`"first"`’, return the first element found. If direction is ‘`"last"`’, return the last element found.

> See also: find, rindex.

— Function File: rindex (s, t)

> Return the position of the last occurrence of the character string t in the character string s, or 0 if no occurrence is found. s may also be a string array or cell array of strings.

> For example:

>               rindex ("Teststring", "t")
>                    ⇒ 6

> The `rindex` function is equivalent to `index` with direction set to ‘`"last"`’.

> See also: find, index.

— Loadable Function: idx = strfind (str, pattern)
— Loadable Function: idx = strfind (cellstr, pattern)

> Search for pattern in the string str and return the starting index of every such occurrence in the vector idx. If there is no such occurrence, or if pattern is longer than str, then idx is the empty array `[]`.

> If a cell array of strings cellstr is specified then idx is a cell array of vectors, as specified above. Examples:

>               strfind ("abababa", "aba")
>                    ⇒ [1, 3, 5]

>               strfind ({"abababa", "bebebe", "ab"}, "aba")
>                    ⇒ ans =
>                       {
>                         [1,1] =

>                            1   3   5

>                         [1,2] = [](1x0)
>                         [1,3] = [](1x0)
>                       }

> See also: findstr, strmatch, regexp, regexpi, find.

— Function File: strmatch (s, A)
— Function File: strmatch (s, A, "exact")

> Return indices of entries of A which begin with the string s. The second argument A must be a string, character matrix, or a cell array of strings. If the third argument `"exact"` is not given, then s only needs to match A up to the length of s. Trailing spaces and nulls in s and A are ignored when matching. option.

> For example:

>               strmatch ("apple", "apple juice")
>                    ⇒ 1

>               strmatch ("apple", ["apple  "; "apple juice"; "an apple"])
>                    ⇒ [1; 2]

>               strmatch ("apple", ["apple  "; "apple juice"; "an apple"], "exact")
>                    ⇒ [1]

> Caution: `strmatch` is scheduled for deprecation. Use `strcmpi` or `strncmpi` in all new code.

> See also: strfind, findstr, strcmp, strncmp, strcmpi, strncmpi, find.

— Function File: [tok, rem] = strtok (str)
— Function File: [tok, rem] = strtok (str, delim)

> Find all characters in the string str up to, but not including, the first character which is in the string delim. If rem is requested, it contains the remainder of the string, starting at the first delimiter. Leading delimiters are ignored. If delim is not specified, whitespace is assumed. str may also be a cell array of strings in which case the function executes on every individual string and returns a cell array of tokens and remainders.

> Examples:

>               strtok ("this is the life")
>                    ⇒ "this"

>               [tok, rem] = strtok ("14*27+31", "+-*/")
>                    ⇒
>                       tok = 14
>                       rem = *27+31

> See also: index, strsplit, strchr, isspace.

— Function File: [cstr] = strsplit (s, sep)
— Function File: [cstr] = strsplit (s, sep, strip_empty)

> Split the string s using one or more separators sep and return a cell array of strings. Consecutive separators and separators at boundaries result in empty strings, unless strip_empty is true. The default value of strip_empty is false.

> 2-D character arrays are split at separators and at the original column boundaries.

> Example:

>               strsplit ("a,b,c", ",")
>                      ⇒
>                         {
>                           [1,1] = a
>                           [1,2] = b
>                           [1,3] = c
>                         }

>               strsplit (["a,b" ; "cde"], ",")
>                      ⇒
>                         {
>                           [1,1] = a
>                           [1,2] = b
>                           [1,3] = cde
>                         }

> See also: strtok.

— Function File: [a, ...] = strread (str)
— Function File: [a, ...] = strread (str, format)
— Function File: [a, ...] = strread (str, format, format_repeat)
— Function File: [a, ...] = strread (str, format, prop1, value1, ...)
— Function File: [a, ...] = strread (str, format, format_repeat, prop1, value1, ...)

> Read data from a string.

> The string str is split into words that are repeatedly matched to the specifiers in format. The first word is matched to the first specifier, the second to the second specifier and so forth. If there are more words than specifiers, the process is repeated until all words have been processed.

> The string format describes how the words in str should be parsed. It may contain any combination of the following specifiers:

> `%s`
>   The word is parsed as a string.
> `%f`
> `%n`
>   The word is parsed as a number and converted to double.
> `%d`
> `%u`
>   The word is parsed as a number and converted to int32.
> `%*', '%*f', '%*s`
>   The word is skipped.

>   For %s and %d, %f, %n, %u and the associated %*s ... specifiers an optional width can be specified as %Ns, etc. where N is an integer > 1. For %f, format specifiers like %N.Mf are allowed.

> `literals`
>   In addition the format may contain literal character strings; these will be skipped during reading.

> Parsed word corresponding to the first specifier are returned in the first output argument and likewise for the rest of the specifiers.

> By default, format is `"%f"`, meaning that numbers are read from str. This will do if str contains only numeric fields.

> For example, the string

>               str = "\
>               Bunny Bugs   5.5\n\
>               Duck Daffy  -7.5e-5\n\
>               Penguin Tux   6"

> can be read using

>               [a, b, c] = strread (str, "%s %s %f");

> Optional numeric argument format_repeat can be used for limiting the number of items read:

> -1
>   (default) read all of the string until the end.
> N
>   Read N times nargout items. 0 (zero) is an acceptable value for format_repeat.

> The behavior of `strread` can be changed via property-value pairs. The following properties are recognized:

> "commentstyle"
>   Parts of str are considered comments and will be skipped. value is the comment style and can be any of the following.
>   - "shell" Everything from `#` characters to the nearest end-of-line is skipped.
>   - "c" Everything between `/*` and `*/` is skipped.
>   - "c++" Everything from `//` characters to the nearest end-of-line is skipped.
>   - "matlab" Everything from `%` characters to the nearest end-of-line is skipped.
>   - user-supplied. Two options: (1) One string, or 1x1 cell string: Skip everything to the right of it; (2) 2x1 cell string array: Everything between the left and right strings is skipped.
> "delimiter"
>   Any character in value will be used to split str into words (default value = any whitespace).
> "emptyvalue":
>   Value to return for empty numeric values in non-whitespace delimited data. The default is NaN. When the data type does not support NaN (int32 for example), then default is zero.
> "multipledelimsasone"
>   Treat a series of consecutive delimiters, without whitespace in between, as a single delimiter. Consecutive delimiter series need not be vertically "aligned".
> "treatasempty"
>   Treat single occurrences (surrounded by delimiters or whitespace) of the string(s) in value as missing values.
> "returnonerror"
>   If value true (1, default), ignore read errors and return normally. If false (0), return an error.
> "whitespace"
>   Any character in value will be interpreted as whitespace and trimmed; the string defining whitespace must be enclosed in double quotes for proper processing of special characters like \t. The default value for whitespace = " \b\r\n\t" (note the space). Unless whitespace is set to ” (empty) AND at least one "%s" format conversion specifier is supplied, a space is always part of whitespace.

> See also: textscan, textread, load, dlmread, fscanf.

— Loadable Function: strrep (s, ptn, rep)
— Loadable Function: strrep (s, ptn, rep, "overlaps", o)

> Replace all occurrences of the substring ptn in the string s with the string rep and return the result. For example:

>               strrep ("This is a test string", "is", "&%$")
>                    ⇒ "Th&%$ &%$ a test string"

> s may also be a cell array of strings, in which case the replacement is done for each element and a cell array is returned.

> See also: regexprep, strfind, findstr.

— Function File: substr (s, offset)
— Function File: substr (s, offset, len)

> Return the substring of s which starts at character number offset and is len characters long.

> Position numbering for offsets begins with 1. If offset is negative, extraction starts that far from the end of the string.

> If len is omitted, the substring extends to the end of S. A negative value for len extracts to within len characters of the end of the string

> Examples:

>               substr ("This is a test string", 6, 9)
>                    ⇒ "is a test"
>               substr ("This is a test string", -11)
>                    ⇒ "test string"
>               substr ("This is a test string", -11, -7)
>                    ⇒ "test"

> This function is patterned after the equivalent function in Perl.

— Loadable Function: [s, e, te, m, t, nm] = regexp (str, pat)
— Loadable Function: [...] = regexp (str, pat, "opt1", ...)

> Regular expression string matching. Search for pat in str and return the positions and substrings of any matches, or empty values if there are none.

> The matched pattern pat can include any of the standard regex operators, including:

> `.`
>   Match any character
> `* + ? {}`
>   Repetition operators, representing
>   `*`
>     Match zero or more times
>   `+`
>     Match one or more times
>   `?`
>     Match zero or one times
>   `{`n`}`
>     Match exactly n times
>   `{`n`,}`
>     Match n or more times
>   `{`m`,`n`}`
>     Match between m and n times
> `[...] [^...]`
>   List operators. The pattern will match any character listed between "[" and "]". If the first character is "^" then the pattern is inverted and any character except those listed between brackets will match.

>   Escape sequences defined below can also be used inside list operators. For example, a template for a floating point number might be `[-+.\d]+`.

> `()`
>   Grouping operator
> `|`
>   Alternation operator. Match one of a choice of regular expressions. The alternatives must be delimited by the grouping operator `()` above.
> `^ $`
>   Anchoring operators. Requires pattern to occur at the start (`^`) or end (`$`) of the string.

> In addition, the following escaped characters have special meaning. Note, it is recommended to quote pat in single quotes, rather than double quotes, to avoid the escape sequences being interpreted by Octave before being passed to `regexp`.

> `\b`
>   Match a word boundary
> `\B`
>   Match within a word
> `\w`
>   Match any word character
> `\W`
>   Match any non-word character
> `\<`
>   Match the beginning of a word
> `\>`
>   Match the end of a word
> `\s`
>   Match any whitespace character
> `\S`
>   Match any non-whitespace character
> `\d`
>   Match any digit
> `\D`
>   Match any non-digit

> The outputs of `regexp` default to the order given below

> s
>   The start indices of each matching substring
> e
>   The end indices of each matching substring
> te
>   The extents of each matched token surrounded by `(...)` in pat
> m
>   A cell array of the text of each match
> t
>   A cell array of the text of each token matched
> nm
>   A structure containing the text of each matched named token, with the name being used as the fieldname. A named token is denoted by `(?<name>...)`.
> sp
>   A cell array of the text not returned by match.

> Particular output arguments, or the order of the output arguments, can be selected by additional opt arguments. These are strings and the correspondence between the output arguments and the optional argument are

> | 'start' | s |
> | 'end' | e |
> | 'tokenExtents' | te |
> | 'match' | m |
> | 'tokens' | t |
> | 'names' | nm |
> | 'split' | sp |

> Additional arguments are summarized below.

> ‘`once`’
>   Return only the first occurrence of the pattern.
> ‘`matchcase`’
>   Make the matching case sensitive. (default)

>   Alternatively, use (?-i) in the pattern.

> ‘`ignorecase`’
>   Ignore case when matching the pattern to the string.

>   Alternatively, use (?i) in the pattern.

> ‘`stringanchors`’
>   Match the anchor characters at the beginning and end of the string. (default)

>   Alternatively, use (?-m) in the pattern.

> ‘`lineanchors`’
>   Match the anchor characters at the beginning and end of the line.

>   Alternatively, use (?m) in the pattern.

> ‘`dotall`’
>   The pattern `.` matches all characters including the newline character. (default)

>   Alternatively, use (?s) in the pattern.

> ‘`dotexceptnewline`’
>   The pattern `.` matches all characters except the newline character.

>   Alternatively, use (?-s) in the pattern.

> ‘`literalspacing`’
>   All characters in the pattern, including whitespace, are significant and are used in pattern matching. (default)

>   Alternatively, use (?-x) in the pattern.

> ‘`freespacing`’
>   The pattern may include arbitrary whitespace and also comments beginning with the character ‘`#`’.

>   Alternatively, use (?x) in the pattern.

> See also: regexpi, strfind, regexprep.

— Loadable Function: [s, e, te, m, t, nm] = regexpi (str, pat)
— Loadable Function: [...] = regexpi (str, pat, "opt1", ...)

> Case insensitive regular expression string matching. Search for pat in str and return the positions and substrings of any matches, or empty values if there are none. See regexp, for details on the syntax of the search pattern.

> See also: regexp.

— Loadable Function: outstr = regexprep (string, pat, repstr)
— Loadable Function: outstr = regexprep (string, pat, repstr, "opt1", ...)

> Replace occurrences of pattern pat in string with repstr.

> The pattern is a regular expression as documented for `regexp`. See regexp.

> The replacement string may contain `$i`, which substitutes for the ith set of parentheses in the match string. For example,

>               regexprep("Bill Dunn",'(\w+) (\w+)','$2, $1')

> returns "Dunn, Bill"

> Options in addition to those of `regexp` are

> ‘`once`’
>   Replace only the first occurrence of pat in the result.
> ‘`warnings`’
>   This option is present for compatibility but is ignored.

> See also: regexp, regexpi, strrep.

— Function File: regexptranslate (op, s)

> Translate a string for use in a regular expression. This may include either wildcard replacement or special character escaping. The behavior is controlled by op which can take the following values

> "wildcard"
>   The wildcard characters `.`, `*`, and `?` are replaced with wildcards that are appropriate for a regular expression. For example:

>                      regexptranslate ("wildcard", "*.m")
>                           ⇒ ".*\.m"

> "escape"
>   The characters `$.?[]`, that have special meaning for regular expressions are escaped so that they are treated literally. For example:

>                      regexptranslate ("escape", "12.5")
>                           ⇒ "12\.5"

> See also: regexp, regexpi, regexprep.

— Function File: untabify (t)
— Function File: untabify (t, tw)
— Function File: untabify (t, tw, deblank)

> Replace TAB characters in t, with spaces. The tab width is specified by tw, or defaults to eight. The input, t, may be either a 2-D character array, or a cell array of character strings. The output is the same class as the input.

> If the optional argument deblank is true, then the spaces will be removed from the end of the character data.

> The following example reads a file and writes an untabified version of the same file with trailing spaces stripped.

>               fid = fopen ("tabbed_script.m");
>               text = char (fread (fid, "uchar")');
>               fclose (fid);
>               fid = fopen ("untabified_script.m", "w");
>               text = untabify (strsplit (text, "\n"), 8, true);
>               fprintf (fid, "%s\n", text{:});
>               fclose (fid);

> See also: strjust, strsplit, deblank.