Main Content

count

计算字符串中模式的出现次数

说明

示例

A = count(str,pat) 返回 patstr 中的出现次数。

如果 pat 是包含多个模式的数组,则 count 返回 pat 的所有元素在 str 中出现的总次数。count 从左到右依次匹配 pat 的元素。str 中的文本段只能匹配一次。

示例

A = count(str,pat,'IgnoreCase',true) 在统计 pat 的出现次数时,将忽略大小写。

示例

全部折叠

对字符串数组中字符串 red 的出现次数进行计数。

您可以使用双引号创建字符串。

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

要计算 red 的出现次数,请使用 count 函数。在本示例中,结果为 2,因为 red 也是单词 paired 的一部分。

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

创建一个 2×1 字符串数组。

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

计算 redstr 的每个元素中的出现次数。如果 str 是字符串数组或字符向量元胞数组,则 A 是具有相同大小的数值数组。

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

     3
     1

自 R2020b 开始提供

创建一个包含地址的字符串数组。

str = ["221B Baker St.","Tour Eiffel Champ de Mars","4059 Mt Lee Dr."]
str = 1x3 string
    "221B Baker St."    "Tour Eiffel Champ de Mars"    "4059 Mt Lee Dr."

要对每个地址中的数字位数进行计数,请首先创建一个匹配单个数字的模式。此模式在字符串中出现的次数等于字符串中的数字位数。

通过调用以 1 作为输入参数的 digitsPattern 函数来创建该模式。当您执行此操作时,它会匹配单个数字(如 2),而不是任意数字序列(如 2214059)。

pat = digitsPattern(1)
pat = pattern
  Matching:

    digitsPattern(1)

然后调用 count 函数且以 strpat 作为输入。

A = count(str,pat)
A = 1×3

     3     0     4

同样,您可以使用 lettersPattern(1) 创建的模式对字母的数量(不包括数字、空格或标点符号)进行计数。

A = count(str,lettersPattern(1))
A = 1×3

     8    21     7

对由一个或多个数字后跟一个字母的序列进行计数。您可以通过组合简单模式来构建更复杂的模式。在本例中,digitsPattern + lettersPattern(1) 匹配 221B

pat = digitsPattern + lettersPattern(1);
A = count(str,pat)
A = 1×3

     1     0     0

有关创建模式对象的函数列表,请参阅pattern

计算 redblue 在字符串数组中出现的总次数。

您可以使用双引号创建字符串。

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

count 为第一个字符串返回 2,因为 redblue 各出现一次。count 为第二个字符串返回 3,因为 red 出现一次,blue 出现两次。

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

     2
     3

计算字母 E 在包含名称的字符串数组中的出现次数,忽略大小写。

您可以使用双引号创建字符串。

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

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

     2
     0

计算 al 在单词 alphabetical 中的出现次数。

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

输入参数

全部折叠

输入文本,指定为字符串数组、字符向量或字符向量元胞数组。

搜索模式,指定为下列值之一:

  • 字符串数组

  • 字符向量

  • 字符向量元胞数组

  • pattern 数组(自 R2020b 开始提供)

扩展功能

版本历史记录

在 R2016b 中推出