convert lower case to upper and upper to lower

21 ビュー (過去 30 日間)
Lauren Kinchla
Lauren Kinchla 2019 年 11 月 21 日
回答済み: Stephen23 2022 年 5 月 23 日
I need help writing a code to flip the case of the characters so that lower case are converted to upper case and upper case characters are converted to lower case and any number values remains unchanged
  1 件のコメント
Star Strider
Star Strider 2019 年 11 月 21 日
There are MATLAB functions to do exactly that! This seems to be homework, so I will defer to you to explore the documentation.

サインインしてコメントする。

回答 (2 件)

Stephen23
Stephen23 2022 年 5 月 23 日
str = '123 Hello World!';
str = regexprep(str,'[A-Za-z]+','${char(mod($&-97,64)+65)}')
str = '123 hELLO wORLD!'

Jan
Jan 2019 年 11 月 21 日
編集済み: Jan 2019 年 11 月 21 日
You can use the function isstrprop with the category 'lower' and 'upper' to identify the specific characters. Then use the commands upper and lower to change the case.
An alternative is to use a comparison:
str = 'aSd12Bqm'
low = (str >= 'a' & str <= 'z')
high = (str >= 'A' & str <= 'Z')
Now upper and lower can be useful again. But you can try it with calculations of the ASCII code also:
str = 'a'
str2 = str + ('A' - 'a')
char(str2)
A smart trick is to flip the 5th bit of the ASCII representation, if the character is a letter:
str = 'Aa'
char(bitxor(double(str), 32))
% 'aA'
% Coversion to DOUBLE is needed, because BITXOR cannot operate on CHARs
You have to use a mask to affect the letters only. See the creation of low and high above, which can be combined.
See:
doc char
doc isstrprop
doc lower

カテゴリ

Help Center および File ExchangeCharacters and Strings についてさらに検索

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by