How to pad zero in string using sprintf

조회 수: 26 (최근 30일)
Nimas
Nimas 2023년 1월 5일
댓글: Fangjun Jiang 2023년 1월 5일
Hello, I have some string
'1010'
'111'
'010'
'10'
'10111'
How to pad zero after the string by using sprint function to be like this
'10100'
'11100'
'01000'
'10000'
'10111'

답변 (3개)

Bora Eryilmaz
Bora Eryilmaz 2023년 1월 5일
This should work on both char arrays as well as strings:
a = { '1010'
'111'
'010'
'10'
'10111'}
a = 5×1 cell array
{'1010' } {'111' } {'010' } {'10' } {'10111'}
b = pad(a, '0')
b = 5×1 cell array
{'10100'} {'11100'} {'01000'} {'10000'} {'10111'}

Fangjun Jiang
Fangjun Jiang 2023년 1월 5일
a={'1010'
'111'
'010'
'10'
'10111'};
b=char(a)
b = 5×5 char array
'1010 ' '111 ' '010 ' '10 ' '10111'
b(b==' ')='0'
b = 5×5 char array
'10100' '11100' '01000' '10000' '10111'

the cyclist
the cyclist 2023년 1월 5일
@Fangjun Jiang gave a great answer for character arrays (which is what you show that you have).
This is a case where MATLAB's new-ish (R2016) string data type might suit your need better, if you can go upstream in your code to use that type.
string = ["1010";
"111";
"010";
"10";
"10111"];
pad(string,"0")
ans = 5×1 string array
"10100" "11100" "01000" "10000" "10111"

카테고리

Help CenterFile Exchange에서 Characters and Strings에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by