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 |
|
7 ## the Free Software Foundation; either version 2, or (at your option) |
|
8 ## any later version. |
|
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 |
|
16 ## along with Octave; see the file COPYING. If not, write to the Free |
5307
|
17 ## Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA |
|
18 ## 02110-1301, USA. |
3789
|
19 |
|
20 ## -*- texinfo -*- |
|
21 ## @deftypefn {Function File} {} strjust (@var{s}, ["left"|"right"|"center"]) |
|
22 ## Shift the non-blank text of @var{s} to the left, right or center of |
|
23 ## the string. If @var{s} is a string array, justify each string in the |
|
24 ## array. Null characters are replaced by blanks. If no justification |
|
25 ## is specified, then all rows are right-justified. |
|
26 ## @end deftypefn |
|
27 |
|
28 function x = strjust (x, just) |
|
29 |
|
30 if (nargin < 1 || nargin > 2) |
|
31 usage ("strjust (s, ['left'|'right'|'center'])"); |
|
32 endif |
|
33 |
|
34 if (nargin == 1) |
|
35 just = "right"; |
|
36 endif |
|
37 |
|
38 just = tolower (just); |
|
39 |
4455
|
40 wfi = warn_fortran_indexing; |
3789
|
41 unwind_protect |
4455
|
42 warn_fortran_indexing = 0; |
3789
|
43 |
|
44 ## convert nulls to blanks |
|
45 idx = find (toascii (x) == 0); |
|
46 if (! isempty (idx)) |
|
47 x(idx) = " "; |
|
48 endif |
|
49 |
|
50 ## For all cases, left, right and center, the algorithm is the same. |
|
51 ## Find the number of blanks at the left/right end to determine the |
|
52 ## shift, rotate the row index by using mod with that shift, then |
|
53 ## translate the shifted row index into an array index. |
|
54 [nr, nc] = size (x); |
|
55 idx = (x' != " "); |
|
56 if (strcmp (just, "right")) |
|
57 [N, hi] = max (cumsum (idx)); |
|
58 shift = hi; |
|
59 elseif (strcmp (just, "left")) |
|
60 [N, lo] = max (cumsum (flipud (idx))); |
|
61 shift = (nc - lo); |
|
62 else |
|
63 [N, hi] = max (cumsum (idx)); |
|
64 [N, lo] = max (cumsum (flipud (idx))); |
|
65 shift = ceil (nc - (lo-hi)/2); |
|
66 endif |
|
67 idx = rem (ones(nr,1)*[0:nc-1] + shift'*ones(1,nc), nc); |
|
68 x = x (idx*nr + [1:nr]'*ones(1,nc)); |
|
69 |
|
70 unwind_protect_cleanup |
4455
|
71 warn_fortran_indexing = wfi; |
3789
|
72 end_unwind_protect |
|
73 |
|
74 endfunction |