在MATLAB中计算字符串中的字数

在MATLAB中计算字符串中的字数,matlab,Matlab,如何计算字符串中的字数 例如: str = 'hi how are you' % Expected: 4 str = 'hi' % Expected: 1 可以使用strsplit在所有空格处拆分字符串(返回一个单元格数组,其中每个元素都是一个单词),然后确定结果单元格数组中的元素数 nWords = numel(strsplit(str)); 或者,如果您有较旧版本的MATLAB,则可以使用regexp为您进行拆分 nWords = numel(regexp(s

如何计算字符串中的字数

例如:

str = 'hi how are you'  % Expected: 4
str = 'hi'              % Expected: 1

可以使用
strsplit
在所有空格处拆分字符串(返回一个单元格数组,其中每个元素都是一个单词),然后确定结果单元格数组中的元素数

nWords = numel(strsplit(str));
或者,如果您有较旧版本的MATLAB,则可以使用
regexp
为您进行拆分

nWords = numel(regexp(str, '\s+', 'split'));

可以使用
strsplit
在所有空格处拆分字符串(返回一个单元格数组,其中每个元素都是一个单词),然后确定结果单元格数组中的元素数

nWords = numel(strsplit(str));
或者,如果您有较旧版本的MATLAB,则可以使用
regexp
为您进行拆分

nWords = numel(regexp(str, '\s+', 'split'));

您可以使用正则表达式:

str = 'hi, how are you?';
matches = regexpi(str, '\w+');
N = numel(matches);

您可以使用正则表达式:

str = 'hi, how are you?';
matches = regexpi(str, '\w+');
N = numel(matches);

如果你不必担心多个空格会把事情搞砸,在16b中你可以这样做

num = count(str,' ') + 1;

如果你不必担心多个空格会把事情搞砸,在16b中你可以这样做

num = count(str,' ') + 1;