Reputation: 21523
How can I turn strings like 1-14
into 01_014
? (and for 2-2
into 02_002
)?
I can do something like this:
testpoint_number = '5-16';
temp = textscan(testpoint_number, '%s', 'delimiter', '-');
temp = temp{1};
first_part = temp{1};
second_part = temp{2};
output_prefix = strcat('0',first_part);
parsed_testpoint_number = strcat(output_prefix, '_',second_part);
parsed_testpoint_number
But I feel this is very tedious, and I don't know how to handle the second part (16
to 016
)
Upvotes: 2
Views: 487
Reputation: 3408
Your textscanning is probably the most intuitive way to do this, but from then on what I would recommend doing is instead converting the scanned first_part
and second_part
into numerical format, giving you integers.
You can then sprintf
these into your target string using the correct 'c'-style formatters to indicate your zero-padding prefix width, e.g.:
temp = textscan(testpoint_number, '%d', 'delimiter', '-');
parsed_testpoint_number = sprintf('%02d_%03d', temp{1});
Take a look at the C sprintf() documentation for an explanation of the string formatting options.
Upvotes: 1
Reputation: 14316
As you are handling integer numbers, I would suggest to change the textscan
to %d
(integer numbers). With that, you can use the formatting power of the *printf
commands (e.g. sprintf
).
*printf
allows you to specify the width of the integer. With %02d
, a 2 chars wide integer, which will be filled up with zeros, is printed.
The textscan
returns a {1x1} cell
, which contains a 2x1
array of integers. *printf
can handle this itsself, so you just have to supply the argument temp{1}
:
temp = textscan(testpoint_number, '%d', 'delimiter', '-');
parsed_testpoint_number = sprintf('%02d_%03d',temp{1});
Upvotes: 1