Enter a string and print it backwards
조회 수: 7 (최근 30일)
이전 댓글 표시
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
2022년 7월 5일
str = 'MATLAB' ;
s = [] ;
n = length(str) ;
for i = n:-1:1
s = [s str(i)];
end
s
답변 (1개)
KSSV
2022년 7월 5일
str = 'MATLAB' ;
% Option 1
flip(str)
% option 2
str(end:-1:1)
For printing, you can use fprintf
fprintf('%s\n',str)
댓글 수: 2
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 Exchange에서 Characters and Strings에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!