how do I count the upper and lowercase letters in a string
Show older comments
I have been able to count the exact letter in a string but I’m having trouble counting the uppercase and lowercase letters for a particular letter in a string using a function. My professor has asked us not to use anything that will oversimplify the script.
5 Comments
Guillaume
on 2 Oct 2019
"My professor has asked us not to use anything that will oversimplify the script."
What a strange statement! Well, we can certainly overcomplicate the code, then.
Mason Krattli
on 2 Oct 2019
Walter Roberson
on 2 Oct 2019
... We do not know what you have learned so far.
Mason Krattli
on 2 Oct 2019
Guillaume
on 2 Oct 2019
Well, the easy way, and I'd argue the right and only way to do it properly in matlab would be to use isstrprop.
num_lower = nnz(isstrprop(yourstring, 'lower'));
num_upper = nnz(isstrprop(yourstring, 'upper'));
which will work properly across the whole unicode range unlike any code you'll be able to come up with which will most likely fail miserably on strings like 'ÑñƂƃ'.
But very likely, you're not allowed to use that. Problem is, we don't know what's in scope or not, so it's difficult to give you an answer.
Answers (4)
Turlough Hughes
on 2 Oct 2019
str='UlUlUlUl'
newStr = upper(str) % make a second string converting the original too all uppercase
% then use strcmp compare the two strings
for ii=1:length(str)
idx(ii)=strcmp(str(ii),newStr(ii));
end
num_uppr=nnz(idx)
num_lwr=length(str)-num_uppr
1 Comment
Guillaume
on 2 Oct 2019
Well, that's certainly one way of overcomplicating things. Note that the loop is not needed, nor strcmp. The whole thing can be simplified to:
num_uppr = nnz(str == upper(str));
num_lwr = numel(str) - num_uppr;
Note that the code will not work for strings containing non-letters, eg. digits, spaces, punctuation, etc.
Walter Roberson
on 2 Oct 2019
if S(K) == 'A' || S(K) == 'B' || S(K) == 'C' | S(K) == 'D' etc
or
if S(K) >= 'A' && S(K) <= 'Z'
but your professor might consider that to be oversimplifying, perhaps.
Later, when you are not under those restrictions, you could consider using ismember() or isstrprop()
Jean Kassa Victoire
on 20 Oct 2022
str = "BEneDicT"
%Extract Letters
A = extractBefore(str,"ict")
%Count upper case letters
pat = characterListPattern('A','Z')
upper_count = count(str,pat)
I'd probably just use isstrprop, but another possibility:
s = 'Abracadabra, Hocus Pocus!';
uppercaseLettersAndNonletters = s == upper(s)
uppercaseLettersOnly = uppercaseLettersAndNonletters & isletter(s)
ULANL = blanks(strlength(s));
ULANL(uppercaseLettersAndNonletters) = s(uppercaseLettersAndNonletters)
ULO = blanks(strlength(s));
ULO(uppercaseLettersOnly) = s(uppercaseLettersOnly)
allThreeStrings = [s; ULANL; ULO]
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!