3789
|
1 ## Copyright (C) 2000 Paul Kienzle |
|
2 ## |
|
3 ## This file is part of Octave. |
|
4 ## |
|
5 ## Octave is free software; you can redistribute it and/or modify it |
|
6 ## under the terms of the GNU General Public License as published by |
7016
|
7 ## the Free Software Foundation; either version 3 of the License, or (at |
|
8 ## your option) any later version. |
3789
|
9 ## |
|
10 ## Octave is distributed in the hope that it will be useful, but |
|
11 ## WITHOUT ANY WARRANTY; without even the implied warranty of |
|
12 ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU |
|
13 ## General Public License for more details. |
|
14 ## |
|
15 ## You should have received a copy of the GNU General Public License |
7016
|
16 ## along with Octave; see the file COPYING. If not, see |
|
17 ## <http://www.gnu.org/licenses/>. |
3789
|
18 |
|
19 ## -*- texinfo -*- |
|
20 ## @deftypefn {Function File} {} strjust (@var{s}, ["left"|"right"|"center"]) |
|
21 ## Shift the non-blank text of @var{s} to the left, right or center of |
|
22 ## the string. If @var{s} is a string array, justify each string in the |
|
23 ## array. Null characters are replaced by blanks. If no justification |
|
24 ## is specified, then all rows are right-justified. |
|
25 ## @end deftypefn |
|
26 |
|
27 function x = strjust (x, just) |
|
28 |
|
29 if (nargin < 1 || nargin > 2) |
6046
|
30 print_usage (); |
3789
|
31 endif |
|
32 |
|
33 if (nargin == 1) |
|
34 just = "right"; |
|
35 endif |
|
36 |
|
37 just = tolower (just); |
|
38 |
5568
|
39 ## convert nulls to blanks |
|
40 idx = find (toascii (x) == 0); |
|
41 if (! isempty (idx)) |
|
42 x(idx) = " "; |
|
43 endif |
3789
|
44 |
5568
|
45 ## For all cases, left, right and center, the algorithm is the same. |
|
46 ## Find the number of blanks at the left/right end to determine the |
|
47 ## shift, rotate the row index by using mod with that shift, then |
|
48 ## translate the shifted row index into an array index. |
|
49 [nr, nc] = size (x); |
|
50 idx = (x' != " "); |
|
51 if (strcmp (just, "right")) |
|
52 [N, hi] = max (cumsum (idx)); |
|
53 shift = hi; |
|
54 elseif (strcmp (just, "left")) |
|
55 [N, lo] = max (cumsum (flipud (idx))); |
|
56 shift = (nc - lo); |
|
57 else |
|
58 [N, hi] = max (cumsum (idx)); |
|
59 [N, lo] = max (cumsum (flipud (idx))); |
|
60 shift = ceil (nc - (lo-hi)/2); |
|
61 endif |
|
62 idx = rem (ones(nr,1)*[0:nc-1] + shift'*ones(1,nc), nc); |
|
63 x = x (idx*nr + [1:nr]'*ones(1,nc)); |
3789
|
64 |
|
65 endfunction |