How can I plus two or more strings?
조회 수: 182 (최근 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!