필터 지우기
필터 지우기

Pad a character array with n zeros

조회 수: 15 (최근 30일)
Michael
Michael 2012년 2월 3일
I know there are formatting tools to pad a certain number of zeros to a number when printing it -- I may be able to use that in some way. But my situation is this: I have binary strings encoded as character arrays: '101010101', etc. I need to have the bit strings to be of a certain length. For example, if that length was 10, '101' would need seven zeros padded on the front: '0000000101', and '111111111' would need one zero padded on the front: '0111111111'.
Is there a quick way where I can have that number of zeros needed (10-numel(num)) padded on the front?
PS - I love the de2bi function where you can specify the number of bits but I am creating really long bit strings and that function only works for numbers less than 2^53-1.

답변 (2개)

Walter Roberson
Walter Roberson 2012년 2월 3일
>> sprintf('%010s', '101')
ans =
0000000101
This is a little obscure but works just fine.
Alternately,
S = '101';
[repmat('0', 1, 10 - length(S)], S]
  댓글 수: 4
Walter Roberson
Walter Roberson 2012년 2월 3일
n = 15;
x = '101';
sprintf('%0*s', n, x)
Sean de Wolski
Sean de Wolski 2012년 2월 3일
Learn something new every day (hour).

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


Sean de Wolski
Sean de Wolski 2012년 2월 3일
To pad a single string:
sprintf('%010s','11');
To pad a cell array of string:
C = {'010';'1';'0111';'01010101'};
D = cellfun(@(x)sprintf('%010s',x),C,'uni',false);

카테고리

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