This is machine translation

Translated by Microsoft
Mouseover text to see original. Click the button below to return to the English verison of the page.

Note: This page has been translated by MathWorks. Please click here
To view all translated materals including this page, select Japan from the country navigator on the bottom of this page.


Substitution in a string

MuPAD® notebooks are not recommended. Use MATLAB® live scripts instead.

MATLAB live scripts support most MuPAD functionality, though there are some differences. For more information, see Convert MuPAD Notebooks to MATLAB Live Scripts.


stringlib::subs(string, substring = replacement, <First>)


stringlib::subs substitutes a substring by another string.

By default, every occurrence of the string substring in string is replaced by replacement. The option First causes only the first appearance of substring to be replaced.

The result is not searched again for instances of substring. See Example 3.

Among several overlapping occurrences of substring, the leftmost one is replaced.


Example 1

The string replacement may be empty.

stringlib::subs("abcdeabcdeabcde", "bc" = "")

Example 2

Every substring is replaced unless the option First is given.

stringlib::subs("abcdeabcdeabcde", "bc" = "xxx")

stringlib::subs("abcdeabcdeabcde", "bc" = "xxx", First)

Example 3

The substitution may produce a new instance of substring, but this one is not replaced.

stringlib::subs("aab", "ab"="b")

Example 4

Collapse all whitespace in strings (see stringlib::collapseWhitespace):

f := proc(x) local y; begin y := 2*x; x + y end_proc:
string := expr2text(f)

string := stringlib::subs(string, "\n" = " "):
string := stringlib::subs(string, "  " = " "):
string := stringlib::subs(string, "  " = " ")



Non empty string


Non empty string that should be replaced


Any string that replaced substring



Determines that only the first appearance of substring in string will be replaced

Return Values

Given string with substring replaced by replacement

Was this topic helpful?