Counting every single symbol in string

6 views (last 30 days)
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!

Answers (2)

dpb
dpb on 4 Jun 2018
Edited: dpb on 4 Jun 2018
[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 Comments
Walter Roberson
Walter Roberson on 4 Jun 2018
You do not use u after you calculate it?
I am not sure why you call unique twice?
dpb
dpb on 4 Jun 2018
changed horses in midstream, Walter, didn't realize hadn't elided first line; the steenkin' edit window is so funky. :(

Sign in to comment.


Walter Roberson
Walter Roberson on 4 Jun 2018
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);

Categories

Find more on Symbolic Math Toolbox 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!