How do I create a function that takes a character array (s) as an input and returns a new character array with each letter shifted forward once in the alphabet?

Assume that the input s will never contain the letter 'z'.
Example:
>> shiftletters('apple')
ans =
bqqmf
So far this is what I have and it must be because I'm an idiot but I can't get any further. Thank you in advance.
* function s = shiftletters('apple')
s=char('[A-Z]'+1);*
I believe my problem lies in the fact that I do not know how to correctly identify the letters of the alphabet into a single variable or array.

4 件のコメント

Yao Li
Yao Li 2013 年 4 月 9 日
What is the correct result for 'apple'? zookd? Think about ASCII characters
Sean
Sean 2013 年 4 月 9 日
編集済み: Sean 2013 年 4 月 9 日
the correct result for 'apple' should be bqqmf. I want to be able to input any words or group of ascii characters and have them shifted to the right 1 step in the alphabet:
'bass' = cbtt
'tree' = usff
etc.
Yao Li
Yao Li 2013 年 4 月 9 日
Do you mean if the string is 12345abcdz23, the result should be 12345bcdea23? Currently, you function runs well except 'z' and the characters beyond alphabet. So before the shift, try to find out whether there are 'z' in the string and which charaters needs to be shifted.
irfan KHAN
irfan KHAN 2020 年 12 月 25 日
can anyone help me in the following
Create a variable named str which contains the characters 'wxyz'. Shift it forwards by three characters (i.e., add 3 to the ascii code). What is the result?

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

 採用された回答

Friedrich
Friedrich 2013 年 4 月 9 日
編集済み: Friedrich 2013 年 4 月 9 日
Hi,
you maybe need to think about the letter z/Z, but in general you can do:
function s = shiftletters(in)
s = char(in+1);
In the case z/Z should stay:
function s = shiftletters(in)
non_z = ~( (in=='z') | (in=='Z'));
s = in;
s(non_z) = char(in(non_z)+1);

その他の回答 (1 件)

Yao Li
Yao Li 2013 年 4 月 9 日
編集済み: Yao Li 2013 年 4 月 9 日
function s=shiftletters(input_string)
for i=1:1:length(input_string)
if((double(input_string(i))>=65&&double(input_string(i))<=89)...
||(double(input_string(i))>=97&&double(input_string(i))<=121))
input_string(i)=char(input_string(i)+1);
elseif((double(input_string(i))==90)||(double(input_string(i))==122))
input_string(i)=char(input_string(i)-25);
end
end
s=input_string;

1 件のコメント

Yao Li
Yao Li 2013 年 4 月 9 日
I just shift z to a and Z to A.
I'm not sure whether it is what you want

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

カテゴリ

ヘルプ センター および File ExchangeVariables についてさらに検索

質問済み:

2013 年 4 月 9 日

コメント済み:

2020 年 12 月 25 日

Community Treasure Hunt

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

Start Hunting!

Translated by