Count number of words per row in a string

6 views (last 30 days)
Angelavtc on 21 Apr 2022
Edited: Les Beckham on 21 Apr 2022
Say I have the following text:
str = [
"an example of a short sentence"
"a second short sentence"]
I would like to count the total number of words per row.
In this case, I want matlab to tell me: 6, 4
I have tried the "count" command, but it is only meant to find specific words.

Image Analyst on 21 Apr 2022
Try this:
str = [...
"an example of a short sentence" ;
"a second short sentence"]
counts = zeros(size(str));
for row = 1 : length(str)
counts(row) = length(strsplit(str(row)));
end

Voss on 21 Apr 2022
I won't claim that this is the best way to do it, or that it'll work for anything you want to consider a "word" in your string array, but here's something:
str = [
"an example of a short sentence"
"a second short sentence"];
arrayfun(@(x)numel(strsplit(x)),str)
ans = 2×1
6 4

Les Beckham on 21 Apr 2022
Edited: Les Beckham on 21 Apr 2022
In 2020b or later you can also use a pattern with a regex pattern to find (and count) words. It took some experimenting to get this right but it works.
str = [
"an example of a short sentence"
"a second short sentence"];
count(str, regexpPattern('\w*'))
ans = 2×1
6 4
If you don't want to allow underscores and numbers in your "words", use this. This allows one optional capital letter only at the beginning of the words.
count(str, regexpPattern('[A-Z]?[a-z]*'))
ans = 2×1
6 4

Categories

Find more on Characters and Strings in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by