如何计算字符串中的字数?
例如:
str = 'hi how are you' % Expected: 4
str = 'hi' % Expected: 1
答案 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;