Documentation Center

  • Trial Software
  • Product Updates

Searching and Replacing

MATLAB® provides several functions for searching and replacing characters in a string. (MATLAB also supports search and replace operations using regular expressions. See Regular Expressions.)

Consider a string named label:

label = 'Sample 1, 10/28/95';

The strrep function performs the standard search-and-replace operation. Use strrep to change the date from '10/28' to '10/30':

newlabel = strrep(label, '28', '30')
newlabel =
   Sample 1, 10/30/95

strfind returns the starting position of a substring within a longer string. To find all occurrences of the string 'amp' inside label, use

position = strfind(label, 'amp')
position =
    2

The position within label where the only occurrence of 'amp' begins is the second character.

The textscan function parses a string to identify numbers or substrings. Describe each component of the string with conversion specifiers, such as %s for strings, %d for integers, or %f for floating-point numbers. Optionally, include any literal text to ignore.

For example, identify the sample number and date string from label:

parts = textscan(label, 'Sample %d, %s');
parts{:}

ans =
           1
ans = 
    '10/28/95'

To parse strings in a cell array, use the strtok function. For example:

c = {'all in good time'; ...
     'my dog has fleas'; ...
     'leave no stone unturned'};
first_words = strtok(c)
Was this topic helpful?