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!