Centering a Text String

The RPG IV language introduces several powerful built-in functions that simplify string-handling requirements. You can add a few more string-related procedures to come up with a complete toolbox for processing text. The Centertext procedure centers a string field, a function that’s handy for centering headings on reports and displays.

Here’s the procedure code for Centertext:

  // ------------------------------------------------------------------
// Procedure name - CenterText
//
// Centers a text string
//
// Return value:
// Centered text string (Char 256)
//
// Parameters:
// Input text string (Char 256)
// Length of result string (Unsigned 5.0)
// (Optional...defaults to 256)
//
// Usage example:
// Heading = CenterText('ABC Company':80);
//
// ------------------------------------------------------------------
H Copyright('(c) Copyright 2003, Bryan Meyers -- www.bmeyers.net')
H NoMain

// ------------------------------------------------------- Prototypes
D CenterText PR 256
D 256 Value
D 5U 0 Value Options(*NoPass)

// --------------------------------------- Begin procedure CenterText
P CenterText B Export
D CenterText PI 256
D InStr 256 Value
D StrLen 5U 0 Value Options(*NoPass)

// --------------------------------------------------- Work variables
D OutStr S 256
D Pos S 5U 0

/FREE
If %Parms = 1;
StrLen = 256;
Endif;

If StrLen > (%Len(%Trim(InStr)) + 1);
Pos = (StrLen - %Len(%Trim(InStr)))/2 + 1;
%Subst(OutStr:Pos) = %Trim(InStr);
Return OutStr;
Else;
Return InStr;
Endif;
/END-FREE

P CenterText E

 

To use the Centertext procedure, a calling procedure must include the following prototype:

  // ------------------------------------------------------- Prototypes
D CenterText PR 256
D 256 Value
D 5U 0 Value Options(*NoPass)

 

When you want to center a text string, you can include the procedure call in an assignment expression. One or two parameters are necessary:

  • the text to be centered (may be an expression)
  • the length of the string in which to center the text (defaults to 256 characters)

 

The procedure returns a 256-byte value, with the text centered in the length you specify:

Heading = Centertext('Company: ' + Cpyname : 80);

 

When you bind the program, be sure to include the module or service program that contains the Centertext procedure:

CRTPGM PGM(library/program) MODULE(library/program library/CENTERTEXT)