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!