필터 지우기
필터 지우기

comparing strings in alphabetical order

조회 수: 17 (최근 30일)
Ella Yeo
Ella Yeo 2019년 5월 29일
답변: Guillaume 2019년 5월 29일
I'm trying to see the which of the input of 2strings(x1,x2) come first alphabetically.(e.g if x1 comes first it will return 1, if x2 comes first it will return -1..)
they need to be in a same length otherwise it doesn't work which is why I did 'MaxLength'.Also I got rid of the blanks in between if it's a sentence.
but I'm trying to compare the ASCII code of each string (a=97) and see which one comes first.
i did this so far but it just won't work.
x1= lower(input('Enter a string: ','s'));
x2= lower(input('Enter a string: ','s'));
x1 = strrep(x1,' ','')
x2 = strrep(x2,' ','')%string replacement
x1_d=double(x1)
x2_d=double(x2)
x1_length=length(x1)
x2_length=length(x2)
maxLength = max([length(x1_d), length(x2_d)])
x1_d(length(x1_d)+1:maxLength) = 0
x2_d(length(x2_d)+1:maxLength) = 0
if x1_d<x1_d
disp('x1 alphabetically procedure x2')
elseif x1_d>x2_d
disp('x2 alpha x1')
else
disp('same')
end
  댓글 수: 1
Stephen23
Stephen23 2019년 5월 29일
편집: Stephen23 2019년 5월 29일
"they need to be in a same length otherwise it doesn't work..."
Because lt operates element-wise. More specifically it follows these rules:
You also need to read the if documentation carefully, to know how it behaves with a non-scalar condition.

댓글을 달려면 로그인하십시오.

답변 (2개)

Stephen23
Stephen23 2019년 5월 29일
Simpler and more robust:
S1 = 'banana';
S2 = 'apple';
[~,X] = sort({S1,S2})
Z = diff(X)
  댓글 수: 2
Ella Yeo
Ella Yeo 2019년 5월 29일
Thank you,
but what if the user entered the exact same word?
Stephen23
Stephen23 2019년 5월 29일
편집: Stephen23 2019년 5월 29일
"but what if the user entered the exact same word?"
Z = diff(X) * ~strcmp(S1,S2)
returns 0 if the words are the same, otherwise -1 or +1. Or you could use an if:
if strcmp(S1,S2)
...
else
...
end

댓글을 달려면 로그인하십시오.


Guillaume
Guillaume 2019년 5월 29일
Even simpler, use strings instead of char vector. Comparison operators work on the whole string instead of on characters
S1 = "banana"
S2 = "apple"
S1 < S2 %returns false
S2 == S2 %returns true
So with your code:
x1 = lower(input('Enter a string: ','s'));
x2 = lower(input('Enter a string: ','s'));
x1 = string(x1);
x2 = string(x2);
if x1 < x2
disp('x1 is before x2 alphabetically')
elseif x1 == x2
disp('x1 and x2 are identical')
else
disp('x1 is after x2 alphabetically')
end

카테고리

Help CenterFile Exchange에서 Characters and Strings에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by