how to concatenate string and number

Hello ,
I want to concatenate string and number in for loop
requestID = Req_Check;
for k = 1 : 10
requestID = requestID +1;
end
I am expecting requestID after for loop like Req_Check_1, Req_Check_2 ...Req_Check_10
How can I do this?

댓글 수: 1

Amir Moslemi
Amir Moslemi 2021년 5월 2일
use "strcat" such that in each iteration convert number to string by "num2str" and eventually strcat(s1,s2). s1 your str and s2 your number(converted to string)

댓글을 달려면 로그인하십시오.

 채택된 답변

Star Strider
Star Strider 2015년 7월 30일

8 개 추천

Two (of perhaps many) possibilities:
requestIDs = 'Req_Check';
for k = 1 : 10
requestID(k,:) = [requestIDs '_' num2str(k,'%02d')]; % Character Array
end
requestIDs = 'Req_Check';
for k = 1 : 10
requestID{k} = [requestIDs '_' num2str(k,'%d')]; % Cell Array
end
The first creates a character array and produces a two-digit number filed so all are of equal length. The second uses a cell array, so the lengths don’t have to be equal.

댓글 수: 4

N/A
N/A 2015년 7월 31일
Thank you Star and Stephen..
Stephen23
Stephen23 2015년 7월 31일
편집: Stephen23 2015년 8월 3일
Using sprintf rather than string concatenation is often clearer and faster:
str = 'Req_Check';
for k = 10:-1:1
out{k} = sprintf('%s_%d',str,k);
end
OR
for k = 10:-1:1
out{k} = sprintf('Req_Check'_%d',k);
end
Thanks again for explanation, then I prefer sprintf here. and I want to find the number from string 'Req_Check_10'. I am using regexp like below:
[D,S]=regexp('Req_Check_10','([0-9])','match')
but its giving me indiviual numbers like 1,0.
Could you please help me on this?
[D,S] = regexp('Req_Check_10','\d+','match','split')

댓글을 달려면 로그인하십시오.

추가 답변 (2개)

cesar silva
cesar silva 2019년 11월 18일

19 개 추천

People like to make all complicated...
Concatenate 2 words
a='hi';
b='you'
c=[a b]
Concatenate word + number
a = num2str(2)
b = 'you'
c = [b a] or... if you want... c = [b '_' a]
will give you: you2 or you_2
SIMPLICITY IS SO SEXY...

댓글 수: 3

Victor Matzkin
Victor Matzkin 2019년 12월 16일
If you think that's simple or intuitive, you're going to freak out when you discver another programming language..
Daniel Posadas
Daniel Posadas 2020년 8월 13일
I'm agree with you, this one helped me out easy and fast... as a sofware engineer I hate when my programmers want to make simple things as if they were very elaborated, wasting resources. Thanks
Bogdan -Ervin
Bogdan -Ervin 2023년 6월 2일
It doesn't give me a single string. It gives me 2 strings for c=[b a] and 3 strings for c=[b '_' a].

댓글을 달려면 로그인하십시오.

MathWorks Support Team
MathWorks Support Team 2024년 6월 11일

0 개 추천

requestID = "Req_Check"
requestIDs = requestID + "_" + (1:10)'
Please see the documentation for strings for more information.

제품

질문:

N/A
2015년 7월 30일

답변:

2024년 6월 11일

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by