Programming

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
```

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

• ```position = findstr('amp', label)
position =
2
```

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

The `strtok` function returns the characters before the first occurrence of a delimiting character in an input string. The default delimiting characters are the set of white-space characters. You can use the `strtok` function to parse a sentence into words. For example,

• ```function allWords = words(inputString)
remainder = inputString;
allWords = '';

while (any(remainder))
[chopped,remainder] = strtok(remainder);
allWords = strvcat(allWords, chopped);
end
```

The `strmatch` function looks through the rows of a character array or cell array of strings to find strings that begin with a given series of characters. It returns the indices of the rows that begin with these characters:

• ```maxstrings = strvcat('max', 'minimax', 'maximum')
maxstrings =
max
minimax
maximum

strmatch('max', maxstrings)
ans =
1
3
```

 String Comparisons Converting from Numeric to String