count

Count occurrences of pattern in strings

Syntax

A = count(str,pattern)
A = count(str,pattern,'IgnoreCase',true)

Description

example

A = count(str,pattern) returns the number of occurrences of pattern in str.

If pattern is an array containing multiple patterns, then count returns the sum of the occurrences of all elements of pattern in str.

example

A = count(str,pattern,'IgnoreCase',true) ignores case when counting the number of occurrences of pattern.

Examples

collapse all

Count the number of occurrences of the sequence of characters, red, in string arrays.

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

str = "paired with red shoes"
str = 
"paired with red shoes"

To count the occurrences of red, use the count function. In this example, the result is 2 because red is also part of the word paired.

A = count(str,"red")
A = 2

Create a 2-by-1 string array.

str = ["red green red red blue blue green";
       "green red blue green green blue"]
str = 2x1 string array
    "red green red red blue blue green"
    "green red blue green green blue"

Count the occurrences of red in each element of str. If str is a string array or cell array of character vectors, then A is a numeric array that has the same size.

A = count(str,"red")
A = 2×1

     3
     1

Count the total number of occurrences of red and blue in a string array.

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

str = ["red green blue";
       "green red blue green blue"]
str = 2x1 string array
    "red green blue"
    "green red blue green blue"

count returns 2 for the first string because red and blue each occur once. count returns 3 for the second string because red occurs once and blue occurs twice.

A = count(str,["red","blue"])
A = 2×1

     2
     3

Count the number of occurrences of the letter E in a string array that contains names, ignoring case.

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

str = ["Edgar Allan Poe";"Louisa May Alcott"]
str = 2x1 string array
    "Edgar Allan Poe"
    "Louisa May Alcott"

A = count(str,'E','IgnoreCase',true)
A = 2×1

     2
     0

Count the number of times al occurs in the word alphabetical.

chr = 'alphabetical'
chr = 
'alphabetical'
A = count(chr,'al')
A = 2

Input Arguments

collapse all

Input text, specified as a string array, a character vector, or a cell array of character vectors.

Search pattern, specified as a string array, a character vector, or a cell array of character vectors.

Extended Capabilities

Introduced in R2016b