count

Counts how many times a piece of text or pattern occurs.

Category: Language Fundamentals > Data Types

Syntax

n = count(str, pat)

Number of non-overlapping occurrences of pat in str.

n = count(str, pat, 'IgnoreCase', true)

Ignores letter case.

Description

Matching scans left to right and each match consumes its characters, so count('aaa', 'aa') is 1, not 2. A search in empty text gives 0. Compare with contains, which only tells whether there is at least one occurrence.

Input arguments

str
Character vector, string array or cell array of character vectors.
pat
Text or pattern object.
'IgnoreCase'
Logical, default false.

Output arguments

n
Array with the size of str; each element is a count.

Example

Occurrences

count('banana', 'an')
count(["banana" "ab"], 'a')
count('Banana', 'a', 'IgnoreCase', true)
Output
ans = 2
ans = 1×2

     3     1
ans = 3

See also

contains strfind startsWith regexp