我正在尝试在Matlab中创建一个简单的程序,用户可以在其中输入字符串(例如“A”,“B”,“AB”或“AB”),程序将输出与我的字母对应的单词
Input | Output
A Hello
B Hola
AB HelloHola
A B Hello Hola
这是我的代码:
A='Hello'; B='Hola';
userText = input('What is your message: ', 's');
userText = upper(userText);
for ind = 1:length(userText)
current = userText(ind);
X = ['The output is ', current];
disp(X);
end
目前我没有得到我想要的结果。我反而得到了这个:
Input | Output
A The output is A
B The output is B
我不完全确定为什么X = ['The output is ', current];
评估为The output is A
而不是The output is Hello
。
该程序如何处理数字......例如1 = "Goodbye"
答案 0 :(得分:4)
发生了什么:
%// intput text
userText = input('What is your message: ', 's');
%// ...and some lines later
X = ['The output is ', userText];
您永远不会将输入的内容映射到变量A
和B
所包含的内容。
他们被称为 A
和B
的事实 与您输入的内容无关。您可以将其称为C
和blargh
,但仍会获得相同的结果。
现在,你可以使用eval
,但这里真的不可取。在这种情况下,使用eval
会强制输入字符串的人知道变量的确切名称......这是可移植性,可维护性,安全性等等等等。
有更好的解决方案,例如,创建一个简单的地图:
map = {
'A' 'Hello'
'B' 'Hola'
'1' 'Goodbye'
};
userText = input('What is your message: ', 's');
str = map{strcmpi(map(:,1), userText), 2};
disp(['The output is ', str]);
答案 1 :(得分:2)
我建议使用地图对象来包含您想要的内容。这将绕过eval
函数(我建议避免像瘟疫一样)。这非常易于阅读和理解,并且非常有效,特别是在长输入字符串的情况下。
translation = containers.Map()
translation('A') = 'Hola';
translation('B') = 'Hello';
translation('1') = 'Goodbye';
inputString = 'ABA1BA1B11ABBA';
resultString = '';
for i = 1:length(inputString)
if translation.isKey(inputString(i))
% get mapped string if it exists
resultString = [resultString,translation(inputString(i))];
else
% if mapping does not exist, simply put the input string in (covers space case)
resultString = [resultString,inputString(i)];
end
end
答案 2 :(得分:0)
查看命令eval
。目前,您正在显示包含所需字符串的变量的名称。 eval
将帮助您实际访问和打印它。
答案 3 :(得分:0)