how to center a string
    22 ビュー (過去 30 日間)
  
       古いコメントを表示
    
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
0 件のコメント
採用された回答
  Peng Li
      
 2020 年 3 月 28 日
        
      編集済み: Stephen23
      
      
 2020 年 3 月 28 日
  
      function out = padline(c, n) if n > length(c) n2add = floor((n - c) / 2); out = [repmat(‘ ‘, 1, n2add) c repmat(‘ ‘, 1, n - length(c) - n2add)]; else out = c; end
typed using cell phone. You may need to replace the ‘ with the correct symbol. Try it.
You may also interested in pad function that works with strings. You can add space to both sides of a string (defined by “ instead of ‘) or a string array.
0 件のコメント
その他の回答 (1 件)
  Stephen23
      
      
 2020 年 3 月 28 日
        str = '23';
num = 9;
tmp = (num-numel(str))/2;
out = sprintf('%*s%*s',fix(tmp)+numel(str),str,ceil(tmp),'')
0 件のコメント
参考
カテゴリ
				Help Center および File Exchange で Characters and Strings についてさらに検索
			
	Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!


