0

Write a script that loads the file words.trimmed and prompts the user to enter a word. Your script should then return every word in the file that differs from the user’s word by only one letter. For example, if the user enters ‘cat’, your script should print out ‘bat’, ‘car’, ‘can’, etc. in the Command Window.

I've been thinking about this problem for a while now but I'm stuck. I need to compare every letter of the word typed in by the user to something, but I dont know what. For every letter that's the same, z=z+1. At the end, if abs(z-length(word typed in by user))<=1, then the word from the word list is presented. But I don't know how to write the code for that. What do I compare it to?

1
  • Do not delete the question just because it is now solved. If an answer below solved your problem, then please accept it by clicking the check mark. If you found a solution to your own problem, then you are welcome to write that as an answer here. Deleting your question is not nice, and will promptly be rolled back. Commented May 23, 2011 at 14:44

1 Answer 1

4

Strings in Matlab are just an array of chars that you can easily compare using ==. This will give you a logical array of the length of the strings with a 1 wherever the strings are identical:

>> a = 'abc'
a =
 abc
>> b = 'abd'
b =
 abd
>> a == b
ans =
 1     1     0

So your comparison could for example be:

num_equal_letters = sum(string1 == string2);
if (num_equal_letters == length(string1) - 1)
    % print string...
end
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.