how to center a string
Show older comments
The goal of this question is to create a function named padLine which inputs a string (char, 1 × N) and a linewidth (integer, scalar). The function then pads the string with spaces (if N<linewidth) in an attempt to center the string the function should output the padded string (char,1xlinewidth).
for example
out=padline('2',9);
disp(out)
xxxx2xxxx
where x is a space
Accepted Answer
More Answers (1)
Stephen23
on 28 Mar 2020
str = '23';
num = 9;
tmp = (num-numel(str))/2;
out = sprintf('%*s%*s',fix(tmp)+numel(str),str,ceil(tmp),'')
Categories
Find more on Characters and Strings in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!