フィルターのクリア

Enter a string and print it backwards

4 ビュー (過去 30 日間)
Shuoze Xu
Shuoze Xu 2022 年 7 月 5 日
コメント済み: KSSV 2022 年 7 月 5 日
Hi.
I'm having a problem with how do I print the string backwards.
Here is my code.
string = input("Please enter a phase: ",'s');
converted_string = []; % Empty phase
for i = length(string):1 % from end to begin
converted_string = [converted_string,string(i)];
end
fprintf("%s converts to %s",string,converted_string);
Expected result: Please enter a phase: There are 18 apples
'There are 18 apples' converts to 'selppa 81 era erehT'
My code result: Please enter a phase: There are 18 apples
There are 18 apples converts to
The first question is that how to add symbol ' on the string?
The second question is that why the result did not have reverse string here?
Thank you all.
  3 件のコメント
KSSV
KSSV 2022 年 7 月 5 日
str = 'MATLAB' ;
s = [] ;
n = length(str) ;
for i = n:-1:1
s = [s str(i)];
end
s
s = 'BALTAM'
Shuoze Xu
Shuoze Xu 2022 年 7 月 5 日
For q1, is that means i need to add ' on the fprintf like that '%s'?

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

回答 (1 件)

KSSV
KSSV 2022 年 7 月 5 日
str = 'MATLAB' ;
% Option 1
flip(str)
ans = 'BALTAM'
% option 2
str(end:-1:1)
ans = 'BALTAM'
For printing, you can use fprintf
fprintf('%s\n',str)
MATLAB
  2 件のコメント
Shuoze Xu
Shuoze Xu 2022 年 7 月 5 日
編集済み: Shuoze Xu 2022 年 7 月 5 日
If i want to use for loop, should i do like that?
string = input("Please enter a phase: ",'s');
old_char = char(string);
new_char = [];
for i = 1:length(old_char)
new_char = [new_char,old_char(end-i+1)];
end
fprintf("'%s' converts to '%s'",string,new_char);
This is something I learned from a post where I was confused about why char() was needed.
KSSV
KSSV 2022 年 7 月 5 日
You may skip that conversion.
old_char = input("Please enter a phase: ",'s');
new_char = [];
for i = 1:length(old_char)
new_char = [new_char,old_char(end-i+1)];
end
fprintf("'%s' converts to '%s'\n",old_char,new_char);

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

カテゴリ

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

タグ

製品


リリース

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by