Convert array of numbers to an array of padded strings

3 ビュー (過去 30 日間)
dormant
dormant 2023 年 9 月 27 日
回答済み: Fangjun Jiang 2023 年 9 月 27 日
I have an array of numbers to convert to an array of strings.
>> stanums = 7:12;
>> stastrings = string( stanums );
stanums =
7 8 9 10 11 12
stastrings =
"7" "8" "9" "10" "11" "12"
How can I have the strings zero-padded? ie "07" "08" etc.
I tried with num2str, but can only manage that using a loop, and I would really like a more elegant way as my code has far too many loops in it already.

回答 (2 件)

Star Strider
Star Strider 2023 年 9 月 27 日
Use the compose function —
stanums = 7:12;
stastrings = compose("%02d", stanums)
stastrings = 1×6 string array
"07" "08" "09" "10" "11" "12"
Note the format descriptor string.
.

Fangjun Jiang
Fangjun Jiang 2023 年 9 月 27 日
stanums = 7:12;
s=sprintf('%02d\n',stanums(:))
s =
'07 08 09 10 11 12 '

カテゴリ

Help Center および File ExchangeCharacters and Strings についてさらに検索

タグ

製品


リリース

R2023b

Community Treasure Hunt

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

Start Hunting!

Translated by