比较Matlab中的第一个字符串

时间:2016-02-26 19:29:56

标签: matlab

我想看看用户输入的字母是否与字典中的任何字词匹配。

有人可以帮我这么做吗?谢谢!

words = {'apple', 'banana', 'bee', 'salad', 'corn', 'elephant', 'pterodactyl'};

user_letter_input = input('Please enter the first letter of a word: ');

for i = words
    if (i starts with user_letter_input)
        disp(['Your new word is: ' i]);
    end
end

2 个答案:

答案 0 :(得分:2)

您可以使用:

if(i{1}(1) == user_letter_input)

答案 1 :(得分:0)

这是一种不同的,无可否认的更为苛刻的方法:

w = char(words); %// convert to 2D char array, padding with spaces
result = find(w(:,1)==user_letter_input); %// test equality with first column

result将是一个带有所有匹配单词索引的向量。例如,

words = {'apple', 'banana', 'bee', 'salad', 'corn', 'elephant', 'pterodactyl'};
user_letter_input = 'b'

将给出

result =
     2
     3
相关问题