Write a Mat lab function called swapcode. m that takes a string txt as input and
ID: 3826412 • Letter: W
Question
Write a Mat lab function called swapcode. m that takes a string txt as input and returns another string swaptxt as output. The function encodes the string by reversing the alphabet: it replaces each 'a' with 'z', each 'b' with 'y', each 'c' with 'x', etc. The function must work for uppercase letters the same way, but it must not change any other characters. Note that if you call the function twice like this txtout = flipcode(flipcode(txtin)) then the string stored in txtout will be identical to the string stored in txtin. The specifications for the function and some sample function calls are shown below. input parameter txt a string output parameter swaptxt a string sample function calls swapcode('This is a sentence.') produces 'Gsrh rh z hvmgvmxv. ' swapcode('Who has a 3 - legged dog?') produces 'Dsl szh z 3-ovttvw wit?' swapcode(swapcode('Dave97')) produces 'Dave 97 'Explanation / Answer
function swaptxt =swapcode(txt)
swaptxt = txt;
for i = 1:length(txt)
if isletter(txt(i)) %considers only alphabets
if txt(i) >= 'A' && txt(i) <= 'M' %for upper half of UPPER case letters
swaptxt(i) = (char)('Z' - (txt(i) - 'A'));
elseif txt(i) >= 'N' && txt(i) <= 'Z' %for lower half of UPPER case letters
swaptxt(i) = (char)('A' + ('Z' - txt(i)));
elseif txt(i) >= 'a' && txt(i) <= 'm' %similarly for lower case
swaptxt(i) = (char)('z' - (txt(i) - 'a'));
elseif txt(i) >= 'n' && txt(i) <= 'z' %and for lower half
swaptxt(i) = (char)('a' + ('z' - txt(i)));
end
end %you are done! hurrah
end
end
I kept the logic of the code as simple as possible. I have also commented the code to make your life easy. Incase you face any trouble understanding the code, please comment below. I shall be glad to help you.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.