I need to create a function that sorts two strings into alphabetical order. any help?
Show older comments
function less=isLess(worda,wordb)
%input:
%worda, wordb = two strings
%output:
%less = true if worda is before wordb. False otherwise
end
Answers (1)
Mark Sherstan
on 13 Nov 2018
Based on your sudo code the following function works
function less = isLess(worda,wordb)
input = {worda, wordb};
inputSorted = sort(input);
if strcmp(input{1},inputSorted{1}) == true
less = true;
else
less = false;
end
end
Otherwise you can just use the first two lines to sort alphabetically.
input = {worda, wordb};
inputSorted = sort(input);
7 Comments
Noah Walker
on 13 Nov 2018
Mark Sherstan
on 14 Nov 2018
Please refer to the following link regarding assignments on MATLAB Answers. I would be happy to help you out further but you need to show some of your own work first.
Noah Walker
on 14 Nov 2018
Mark Sherstan
on 14 Nov 2018
You are close. May I suggest using ASCII? I used a very similar method to yours it is just easier to work with numbers then letters. I make the following assumption that there are no spaces and all words are input as lowercase (you can easily add failsafes at the start of the function to make the string meet these requirments).
function out = alphabeticalOrder(worda,wordb)
% Convert to ASCII
wordA = double(worda);
wordB = double(wordb);
% Find the smaller word length as min function cant be used
if length(wordA) <= length(wordB)
k = 1;
else
k = 0;
end
% Compare each letter ASCII value to find if sorted correctly
for ii = 1:(length(wordA)*(k) + length(wordB)*(1-k))
% If the same letter go to next ii value
if wordA(ii) == wordB(ii)
continue
end
% If letter of worda before wordb true, otherwise false. Smaller number corresponds to start of alphabet.
if wordA(ii) > wordB(ii)
out = false;
return
else
out = true;
return
end
end
% Do a final check based off word length
if length(wordA) > length(wordB)
out = false;
return
end
out = true;
end
Noah Walker
on 14 Nov 2018
Walter Roberson
on 14 Nov 2018
ii is not a function it is just aa variable being used as a for loop index
Noah Walker
on 14 Nov 2018
Categories
Find more on Shifting and Sorting Matrices 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!