How can I plus two or more strings?
66 次查看(过去 30 天)
显示 更早的评论
I have:
person=[1,2];
for i=1:length(person)
if (person(i))== 1
str=sprintf('Person A');
elseif (output(i))==2
str=sprintf('Person B');
elseif (output(i))==3
str=sprintf('Person C');
elseif (output(i))==4
str=sprintf(' Person D');
elseif (output(i))==5
str=sprintf('Person E');
else
str=sprintf('System can not detect!');
end
end
% How can I plus result in each loop, like this:
str='Person A Person B'
Thank for your help!
0 个评论
回答(2 个)
Ced
2016-3-12
编辑:Ced
2016-3-12
Version 1:
You can concatenate two strings like matrix elements, i.e.
str1 = 'Person A ';
str2 = 'Person B ';
str = [ str1 str2 ]
Version 2: Since you are not actually using the output, I would do:
person = [ 1 2 ];
str_all = {'Person A ', 'Person B ', 'Person C ', 'Person D ', 'Person E '};
str = [ str_all{person} ];
No need for any loop or if statements.
If the last space bothers you, just remove it at the end with
str(end) = '';
0 个评论
Steven Lord
2016-3-12
Some languages use + to concatenate strings. In MATLAB, however, you concatenate character arrays the same way you concatenate other types of arrays: using square brackets.
x = 1:5;
y = 6:10;
z = [x, y] % 1:10
w1 = 'abra';
w2 = 'cadabra';
w = [w1, w2] % 'abracadabra'!
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Characters and Strings 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!