Counting every single symbol in string
显示 更早的评论
Hello everybody, I'm trying to solve the problem with counting symbols in a string. I have to count every single symbol in sting and write them in a command window. My idea is to use ASCII to transfer every single symbol to an ASCII code and then count the frequency of occurrence. But I dont know if there is some command to cover that huge scale of symbols and count each of them. Do you have guys any idea? Thank you for your time!
回答(2 个)
[c,~,idx]=unique(s); % unique elements, location in the string 's'
n=histcounts(idx,numel(c)); % count how many of each
Above keeps case separate; 'a' and 'A' will be different. If they're to be the same then use
u=unique(lower(s));
2 个评论
Walter Roberson
2018-6-4
You do not use u after you calculate it?
I am not sure why you call unique twice?
dpb
2018-6-4
changed horses in midstream, Walter, didn't realize hadn't elided first line; the steenkin' edit window is so funky. :(
Walter Roberson
2018-6-4
The short method of counting is
n = accumarray(1+TheCharacterVector(:), 1);
The count for the ASCII code K would be in array entry K+1. You could proceed from there to
[CODE, ~, count] = find(n);
Symbol = char(CODE-1);
But unique is cool too:
[Symbol, ~, bin] = unique(TheCharacterVector(:));
count = accumarray(bin, 1);
类别
在 帮助中心 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!