How can I change the upper case letters in a string to lowercase while also changing the lowercase letters to uppercase?

53 ビュー (過去 30 日間)
I am tying to figure out how to basically make all the characters in a string change case. So all uppercase to lowercase and all lowercase to uppercase. I have tried using lower to make all capital letters lowercase, but then I run into the problem where now all the characters are lowercase so now if I go to use upper it will all become uppercase. I would like to know how to get around this, maybe not the full solution but an hint, I am thinking a for loop would be good for this, but I am not sure.
  1 件のコメント
Stephen23
Stephen23 2021 年 11 月 19 日
Just for fun:
str = 'Hello World!';
regexprep(str,'[A-Za-z]+','${char(mod($&-97,64)+65)}')
ans = 'hELLO wORLD!'

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

回答 (2 件)

Rik
Rik 2021 年 11 月 19 日
No need for a loop.
There are three 'types' of characters that are potentially in your string:
  1. Upper case characters
  2. Lower case characters
  3. Symbols without defined case (comma, period, etc)
I would create an array that encode the type. To do this you need to create an upper case and a lower case version of your string (with upper and lower). If you use a char array instead of a string, that will allow you to do element-wise comparisons.
txt='Aa.';
upper(txt)==lower(txt)
ans = 1×3 logical array
0 0 1
That is how you can find the position of type 3. You can use a similar tactic to find type 1 and 2. Then you can use logical indexing to replace the appropriate characters.
You can also ignore type 3, since those don't change, so it doesn't matter whether you copy the 'lower case' period or the 'upper case' period.

Alex Alex
Alex Alex 2021 年 11 月 19 日
編集済み: Alex Alex 2021 年 11 月 19 日
Try begin with this example
clc
clear
a='Hello My BROthEr'; % text in one row
for i=1:length(a)% cycle from 1 to size massive
tf=isstrprop(a(1,i),'lower');% check lower or no register in position of symbol
if tf==1% if lower
b(1,i)=upper(a(1,i));%
else % if upper
b(1,i)=lower(a(1,i));%
end
end
  3 件のコメント
Rik
Rik 2022 年 5 月 21 日
@Qasim, what code exactly? And why? What doesn't work about either answer?

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

タグ

製品


リリース

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by