How do I "backward" a string in matlab: turn "a" into "z", "b" into "y", "c" into "x", etc.
Show older comments
I used the following code, but got an error...
function output_string = codeit(txt);
for ii = 1:length(txt)
input_char = txt(ii);
if input_char>='a'&&input_char<='z';
reverse_alphabet= ['z' 'y' 'x' 'w' 'v' 'u' 't' 's' 'r' 'q' 'p' 'o' 'n' 'm' 'l' 'k' 'j' 'i' 'h' 'g' 'f' 'e' 'd' 'c' 'b' 'a'];
reverse_alphabet_index = input_char - 'a' + 1;
output_char = reverse_alphabet(reverse_alphabet_index);
output_string(ii) = output_char;
elseif input_char>='A'&&input_char<='Z';
reverse_alphabet= ['Z' 'Y' 'X' 'W' 'V' 'U' 'T' 'S' 'R' 'Q' 'P' 'O' 'N' 'M' 'L' 'K' 'J' 'I' 'H' 'G' 'F' 'E' 'D' 'C' 'B' 'A'];
reverse_alphabet_index = input_char - 'A' + 1;
output_char = reverse_alphabet(reverse_alphabet_index);
output_string(ii) = output_char;
end
end
end
ans =
Feedback: Your function performed correctly for argument(s) 'azAZ'
Feedback: Your program made an error for argument(s) '`_^]\[ {|}~'
Your solution is _not_ correct.
3 Comments
Guillaume
on 1 Jun 2015
Note that
reverse_alphabet= ['z' 'y' 'x' 'w' 'v' 'u' 't' 's' 'r' 'q' 'p' 'o' 'n' ...
is exactly the same as
reverse_alphabet= 'zyxwvutsrqpon...'
The latter of course being much easier to type. Probably even better would be:
reverse_alphabet= 'z':-1:'a'; %or fliplr('a':'z')
@Darshan Kanungo: What is the specified/expected output for the input string '`_^]\[ {|}~' ? This is currently not specified in the question or the error message, so we have no idea how the function should behave with non-alphabetic characters. You need to specify this for us!
Darshan Kanungo
on 1 Jun 2015
Accepted Answer
More Answers (2)
Jan
on 1 Jun 2015
function out = codeit(in)
lut = char(1:255);
lut(['a':'z', 'A':'Z']) = ['z':-1:'a', 'Z':-1:'A'];
out = lut(in);
charu sharma
on 26 Aug 2015
0 votes
For a simple understanding you can follow this too: http://farzicoders.blogspot.in/2015/08/write-function-called-codeit-that-takes.html
1 Comment
Guillaume
on 26 Aug 2015
I wouldn't classify this answer as spam, the link is relevant to the question (as long as it does not disappear).
However, the answer posted in the link is a poor example of coding (unnecessary loops, unnecessary conversions, unnecessary use of temporary variables), so is of little value.
Categories
Find more on Historical Contests 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!