Modern ABAP

String Processing

(C) Brandeis Consulting

Survey – What Do You Know?

Which ABAP statements/commands/functions for string processing do you know?

Please write them on a card and pin them to the board.

(C) Brandeis Consulting

Overview

  • Character fields and strings
  • Concatenation operator
  • String functions
  • String templates
(C) Brandeis Consulting

Character Fields and Strings

Not new, but important!

Character fields – internal ABAP type c

DATA lv_char(10) TYPE c
                 VALUE 'Brandeis '.
WRITE lv_char && lv_char.

For this data type, trailing spaces are always removed.
This applies even to character literals, which are written using regular quotation marks.

Text strings – internal ABAP type string

DATA lv_string TYPE string
               VALUE `Brandeis `.
WRITE lv_string && lv_string.

For strings, spaces are preserved —
but only if the literal was written using backquotes (```) in the source code.
Unfortunately, most people don’t even know how to type these backquotes on a German keyboard. :-)

Trailing spaces are removed for character fields, but not for strings!

(C) Brandeis Consulting

Concatenating Strings

Concatenation Operator &&

The concatenation operator && combines two strings.
This is much cleaner than using CONCATENATE,
and it also works in operand positions without helper variables.

CONCATENATE 'ABC' 'DEF' 'GHI' INTO resultstring1.
resultstring2 = 'ABC' && 'DEF' && 'GHI'.

Appending with &&=

resultstring3 = 'ABC'.
resultstring3 &&= 'DEF'.
resultstring3 &&= 'GHI'.

Each results in 'ABCDEFGHI'.

(C) Brandeis Consulting

String Functions – Overview

SAP Documentation: String Functions

String functions use named parameters,
so you need to know the parameter names. :-(
Fortunately, the F1 help shows which parameters are expected.

--Jörg ==> Joerg
replace( val = text
         sub = 'ö'
         with = 'oe' )
(C) Brandeis Consulting

String Functions – List

Most Common Functions

  • substring, substring_* – Substrings, also with regular expressions
  • replace – Replace by position & length or with regular expressions
  • match – Substring that matches a regular expression
  • to_upper, to_lower – Change to upper/lower case
  • translate – Character-by-character replacement
  • concat_lines_of – Concatenate table lines
  • condense – Remove characters from the beginning/end and optionally reduce duplicates inside
(C) Brandeis Consulting

String Functions – Continued

  • reverse – Reverse the string character by character
  • segment – Substring similar to “split”
  • shift_left, shift_right – Shift functions
  • to_mixed, from_mixed – Convert to and from CamelCase
  • escape – Escape text (e.g., for URLs)
  • insert – Insert text into another text at a specific position
  • cmax, cmin – Character-based max/min functions
(C) Brandeis Consulting

Examples – substring

substring( val = 'joerg@brandeis.de' off = 3 len = 3 )rg@

substring_from( val = 'joerg@brandeis.de' sub = '@' )@brandeis.de

substring_after( val = 'joerg@brandeis.de' sub = '@' )brandeis.de

substring_before( val = 'joerg@brandeis.de' sub = '@' )joerg

substring_to( val = 'joerg@brandeis.de' sub = '@' )joerg@

(C) Brandeis Consulting

Typical Parameters

  • val – The text
  • sub – The substring to search for
  • off – Offset (number of characters to skip)
  • len – Length of substring
  • del – What to delete
  • with – Replacement text
  • case – Case-sensitive or not
  • occ – Occurrence number; 0 = all occurrences
(C) Brandeis Consulting

Regular Expressions

“A regular expression (regex or regexp) is a sequence of characters that defines a search pattern.” (Wikipedia)

ABAP functions use Perl Compatible Regular Expressions (PCRE)

(C) Brandeis Consulting

Examples – Replacement with Regular Expressions

  • \b([0-9]{1,2})\.([0-9]{1,2})\.([0-9]{4})\b finds date values in a text.
    It looks for three blocks of digits separated by dots, with lengths 1–2, 1–2, and 4.
    The date’s plausibility is not checked — so even 32.3.2017 would match.
    A stricter check is possible, but requires a more complex regex.

Example text for testing on the next slide

(C) Brandeis Consulting

Example Text Containing Dates

Jörg:

“Generate a text with many date values in format MM.DD.YYYY”

ChatGPT:

Sure! Here’s an example text with many date values in the format MM.DD.YYYY:
On 03.28.2023 an important international summit began, lasting until 04.02.2023.
Leaders from around the world met to discuss global issues such as climate change, the economy, and peace.
The event took place in a large conference hall that opened on 03.25.2023.
On 03.30.2023 there was a major press conference where the results were presented.

Note: The dates are in an inconvenient format! Let’s replace them.

(C) Brandeis Consulting

Regular Expressions in Functions

Available in the following functions:

  • match
  • replace
  • substring
(C) Brandeis Consulting

Example – match

Extract the last name from an email address.

(C) Brandeis Consulting

Example – replace

With and without regular expressions:

--Jörg ==> Joerg
replace( val = text
         sub = 'ö'
         with = 'oe' )

--Peter Pan ==> Pan, Peter
replace( val = text
         pcre = '(.*)\s(.*)'
         with = '$2, $1' )
(C) Brandeis Consulting

String Templates

Expressions that create strings.
They consist of literals and may include embedded expressions, formatting, and control characters.
SAP Documentation: String Templates

Example

DATA(thema) = |String Templates|.
DATA(satz) = |This is an example for the topic { thema }|.
DATA(n) = |{ satz }, which we will discuss on { sy-datum }|.
out->write( satz ).

Syntax

  • Start and end are marked by a vertical bar |.

  • Everything in between is constant text, except:

    • { }Embedded expressions, optionally with formatting
    • Control characters
  • The characters {, }, |, and \ must be escaped with a backslash.

(C) Brandeis Consulting

Embedded Expressions

Within string templates, you can use embedded expressions.

Syntax

{ expression [format] }

  • Enclosed in curly braces
  • Spaces recommended at start and end
  • Formatting is optional

Possible Expressions

  • Variables and data objects
  • Operator expressions (calculations)
  • Constructor expressions
  • Table expressions
  • Function calls or functional method calls
(C) Brandeis Consulting

Examples of Embedded Expressions

  • |Today is { sy-datum }|
  • |{ sy-dbcnt / 1000 } thousand records have been changed|
  • |Calling method { new classname()->get_name() }|
(C) Brandeis Consulting

Formatting of Embedded Expressions (1/2)

SAP Documentation: Formatting Options

General Formatting

WIDTH – Length of placeholder for the expression
ALIGN – Alignment if shorter than WIDTH
PAD – Padding character if shorter than WIDTH
CASE – Convert to upper/lower case
ALPHA – Alpha conversion
XSD – Convert to XML data format

(C) Brandeis Consulting

Formatting of Embedded Expressions (2/2)

Numeric Formatting

SIGN – Position/display of sign
EXPONENT – Scientific notation exponent
DECIMALS – Number of decimal places
ZERO – Display of zero
STYLE – Decimal float format
NUMBER – User-specific or standard number format
CURRENCY – Currency used to determine decimal places

Date/Time Formatting

DATE – Date formatting options
TIME – Time formatting options
TIMESTAMP – Timestamp formatting options
TIMEZONE – Local time zone for UTC conversion

COUNTRY – Country-specific formatting for numbers or times

(C) Brandeis Consulting

Control Characters in String Templates

Line breaks and tabs can be used directly within string templates:

  • \r – Carriage return
  • \n – Line feed
  • \t – Tab

This makes CL_ABAP_CHAR_UTILITIES=>CR_LF unnecessary.

(C) Brandeis Consulting

Exercise – String Templates

Task

Create a method that generates a greeting for a person from table ZBC_USERS,
including a note about their next birthday.

Method Signature

METHODS get_salutation IMPORTING user_id TYPE char12
                       RETURNING VALUE(result) TYPE string.

Invocation from the MAIN method

METHOD if_oo_adt_classrun~main.
  out->write( get_salutation( user_id = 'PMUELLER' ) ).
ENDMETHOD.

Example data from table ZBC_USERS (excerpt)

USER_ID FIRSTNAME LASTNAME DATE_OF_BIRTH GENDER ...
0000000001 Peter Müller 20010101 M
0000000002 Siegfried Mustermann 19790203 M
0000000003 Petra Maier 19820304 F

Example Output

Hello Mr. Peter Müller, you will celebrate your 22nd birthday in 43 days!

(C) Brandeis Consulting

Links

(C) Brandeis Consulting

Clean Code Recommendations

  • Method names should not exactly match function names —
    a method named replace will cause confusion.
  • Functions are usually better than statements for string processing,
    as no helper variables are needed.
  • Instead of text = |{ text } abc|, write elegantly:
    text &&= | abc|
(C) Brandeis Consulting