计算MATLAB中字符串中的单词数

时间:2016-09-28 21:49:11

标签: matlab

如何计算字符串中的字数?

例如:

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

3 个答案:

答案 0 :(得分:4)

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

nWords = numel(strsplit(str));

或者,如果您有旧版本的MATLAB,可以使用regexp为您进行拆分。

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

答案 1 :(得分:1)

您可以使用正则表达式:

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

答案 2 :(得分:0)

如果您不必担心多个空间搞砸了,那么在16b你可以做到

num = count(str,' ') + 1;
相关问题