MATLAB Programming Fundamentals - MathWorks

(やまだぃちぅ) #1

Search and Replace Text


You can search for text in character arrays and string arrays, and replace substrings with
new text. String arrays, and new functions to search for and replace text, were introduced
in R2016b. Search for substrings with functions such as the contains function. Similarly,
replace text in strings with the replace function, or extract text with functions such as
extractBetween. You can use any of these functions with either character vectors or
string arrays. For compatibility, you can also use functions such as strfind and strrep
with both character vectors and string arrays.

Search for Text

Identify text in string arrays, character vectors, or cell arrays of character vectors with
the contains, startsWith, and endsWith function.

Create a string. Starting in R2017a, you can create strings using double quotes.

str = "Rosemary Jones"

str =
"Rosemary Jones"

Determine whether str contains the substring mary. The contains function returns a
logical 1 if it finds the substring any place within the string.

TF = contains(str,"mary")

TF = logical
1

You can also use the strfind function to find matching text. strfind returns the index
of the start of each match. In this case, strfind returns 5 because the m in mary is the
fifth character of str.

idx = strfind(str,"mary")

idx = 5

Find multiple matches with strfind. When there are multiple matches, strfind returns
the indices as an array.

idx = strfind(str,"s")

6 Characters and Strings

Free download pdf