0% found this document useful (0 votes)
341 views16 pages

ABAP String Operations Overview

String templates in ABAP allow embedding expressions within literal text in string variables. A string template is defined between pipe (|) characters and can contain literal text segments as well as embedded expressions enclosed in curly brackets. Embedded expressions are evaluated and their values inserted into the string. Common string operations in ABAP include concatenation, translation, replacement, splitting, shifting, searching, and comparison of strings.

Uploaded by

Surendra P
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
341 views16 pages

ABAP String Operations Overview

String templates in ABAP allow embedding expressions within literal text in string variables. A string template is defined between pipe (|) characters and can contain literal text segments as well as embedded expressions enclosed in curly brackets. Embedded expressions are evaluated and their values inserted into the string. Common string operations in ABAP include concatenation, translation, replacement, splitting, shifting, searching, and comparison of strings.

Uploaded by

Surendra P
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
  • String Operations in ABAP

String Operations In ABAP

String Operations:
String is the variable length data type
Dynamic memory management is used internally i.e the memory allocation at the run
time according to the current field content
Note: we can’t declare the string variable through PARAMETER
PARAMETER p_name type String. Is not allowed because the system can’t understand
how big it is
Difference between the character and string:
Character String
Data: v1 type char50. Data:v1 type string.
V1 = ‘Career it’. V1 = ‘Career it’.

Here memory is always allocated for 50 Here memory is allocate for ‘Career it’
characters irrespective of number of only because always string size depends
characters should be stored currently on number of characters should be stored
currently

String operations:
CONCATENATE: to join more than one substring into one variable
Syntax:
CONCATENATE <String1> <string2>………<string N> into <str> separated by
<Separator>
Ex :
*&---------------------------------------------------------------------*
*& Report  ZVISHNU_STRING_OPERATIONS
*&---------------------------------------------------------------------*

REPORT  ZVISHNU_STRING_OPERATIONS NO STANDARD PAGE HEADING.
*//declare varibles
data :str1 type string.
*//concatenating the strings
CONCATENATE 'Career it' 'Ammerpet' 'hyd' INTO str1 SEPARATED BY ','.
*//Displaying output
write:/ str1.
Output:

CONDENSER: replace the sequence of spaces into one space


Ex: CONDENSER ‘Career                it’.
Result: Career it
Ex: CONDENSER ‘Career                it’ NO-GAPS.
Result: Careerit

TRANSLATE: to translate to UPPER / LOWER case


*&---------------------------------------------------------------------*
*& Report  ZVISHNU_STRING_OPERATIONS
*&---------------------------------------------------------------------*

REPORT  ZVISHNU_STRING_OPERATIONS NO STANDARD PAGE HEADING.
*//declare varibles
data :str1 type string.
* Assigning values to those variables
str1 = 'career it'.

*//Traslate the string into Uppercase
TRANSLATE str1 TO UPPER CASE.
*//Displaying output
write:/ str1.

REPLACE:
Syntax :
REPLACE <str1> with <str2> into <str>.
*&---------------------------------------------------------------------*
*& Report  ZVISHNU_STRING_OPERATIONS
*&---------------------------------------------------------------------*

REPORT  ZVISHNU_STRING_OPERATIONS NO STANDARD PAGE HEADING.
*//declare varibles
data :str1 type string,
      str2 type string,
      str3 TYPE string.
* Assigning values to those variables
str1 = 'c'.
str2 = 'i'.
str3 = 'Career it'.

*//Replacing the stings
REPLACE  str2 WITH str1 INTO str3.
*//Displaying output
write:/ str3.
SPLIT: to split the main string into substrings at the given separator
SPLIT <String> AT <separator> into <str1> <str2>…….<str N>.
*//declare varibles
data :v_id TYPE char20,
      v_name TYPE char20,
      v_place TYPE char20,
      v_city TYPE char20.
*//Calling the split
SPLIT 'c001, Careerit, ammerpet, hyd ' at ',' INTO v_id v_name v_place v_city.
*//Displaying output
write: v_id, v_name, V_place, v_city.

SHIFT: By default shift to left by one place


SHIFT <str> <LEFT/RIGHT/CIRCULAR> by <N> places. (N>0)
SHIFT <str> LEFT DELETING LEADING <CHAR>
SHIFT <str> RIGHT DELECTING TRAILING <CHAR>.

SEARCH: searches for the required main string in the main string


SEARCH <str> FOR <str1>.
SEARCH string1 FOR string2 STARTING AT position1 ENDING AT position 2.
-       position1 and position2 are starting ending line of internal tables.

Comparing strings:
                Operator Description
                   CO Contains only
                   CN Contains not only
                   CA Contains any
                   NA Contains not only
                   CS Contains String
                    NS Contains no String
                    CP Matches pattern
                    NP Does not Matches pattern

CO(Contains only):
IF <str1> CO <str2>.
Is TRUE if string1 contains only the characters from string2 the comparison is case
sensitive including spaces
If the comparison  is true then the system field SY-FDPOS contains the length of string1
If it is false then SY-FDPOS contains the offset of the first character of string1 that does
not occur in string2
Examples:
•         'AABB' co 'AB' True
•         'ABCD' co 'ABC' False
•         'AABB' cn 'AB' False
•         'ABCD' cn 'ABC' True
•         'AXCZ' ca 'AB' True
•         'ABCD' ca 'XYZ' False
•         'AXCZ' na 'ABC' False
•         'ABCD' na 'XYZ' True 

1) What is the ABAP code to find the last three characters of a string?
Sol:
data : lv_string type string.
SHIFT lv_string RIGHT CIRCULAR BY 3 PLACES.
WRITE lv_string(3).
String Template:

A string template is enclosed between two "|" characters and can only be specified in a string
expression of a Unicode program. A string template creates a character string that is used by the string
expression instead of the string templates. The characters of this character string consist of any
sequence of the following syntax elements of the string template

String expression

Formulation of an operation with character-like operands in a calculation expression


whose result is a character string.

Character String

String of alphanumeric characters. Content of a character-like data object. Also known as


a character sequence.

Unicode Program

A Unicode program is an ABAP program in which the Unicode checks are run and in
which certain statements involve different semantics from those that apply in non-
Unicode programs. A program of this kind usually returns the same results in a Unicode
system as in a non-Unicode system.

 Literal text literal_text

 Embedded expressions embedded_expressions

 Control characters control_characters

A string template that starts with "|" must be closed with "|" within the same line of source code.
The only exceptions to this rule are line breaks in embedded expressions. There are, however, no
length restrictions on a string template. The literal operator & or the chaining operator && can
be used to join multiple string templates in a single string template. A string template can be
defined across multiple lines of source code and be given comments.
String Templates - Literal_text

Syntax

c...c

Effect

Within a string template |...|, a literal text c...c represents its exact character string. Literal text
consists of all characters in c that

 are not enclosed in curly brackets { }

 are not control characters

 are not the special characters |, {, }, or \.

Blanks in string templates in particular are always significant. To display a special character |,
{, }, or \ as a literal character, it can be prefixed with the escape character \.

Example

The following string template displays the text "Characters |, {, and } have to be escaped by \ in
literal text.".

DATA txt TYPE string.

txt = |Characters \|, \{, and \} have to be escaped by \\ in literal text.|.


String Templates - embedded_expressions

Syntax : { expr [format_options] }

Effect : Within a string template, an opening and a closing curly bracket { ... } define a general
expression position expr in which

 data objects,

 calculation expressions,

 constructor expressions,

 table expressions,

 predefined functions, or

 functional methods and method chainings

can be specified in ABAP syntax. At least one blank must be included on the right of the opening
bracket and one the left of the closing bracket. An embedded expression must be complete within
the current string template. An embedded expression within the curly brackets is handled in
accordance with regular ABAP syntax:

 Tokens must be separated by at least one blank or line break.

 In other cases, blanks and line breaks between tokens are not significant.

 No distinction is made between uppercase and lowercase letters.

 Comments can be specified.

The data type of the expression must be an elementary data type and the value of the expression
must be character-like or be convertible to a string. When a string template is analyzed, the value
of each embedded expression is converted to a character string. The string is inserted in the
correct location. The string is formatted either using

 predefined formats or

 formatting options format_options.

The embedded expressions in a string template are analyzed from left to right. If function
methods are specified, they are executed during the analysis.
Notes

 Unlike other syntax representations in the ABAP key word documentation, the curly
brackets are part of the syntax.

 To display the curly brackets { and } in literal text in a string template, they must be
prefixed with the escape character \.

 Curly brackets cannot be nested directly. If expr is itself a string expression, or contains a
string expression, then it can contain embedded expressions.

 String functions with character-like return values are recommended when embedded
functions are specified.

 Unlike arithmetic expressions and bit expressions, embedded functional methods are not
executed before the whole expression is analyzed. If an embedded functional method
modifies the value of data objects that are also used as embedded operands, the change
only affects data objects on the right of the method.

 The delimiter characters "|" can be formatted in the new ABAP Editor by choosing Fonts
and Colors → Token operator to highlight them in the source code.

data object

 Instance of a data type. Exists in the internal session of an ABAP program or as a shared
object in the shared memory. Is created either as a named, statically declared data object
(statement DATA and similar) when a program or procedure is loaded, or dynamically as
an anonymous data object at runtime (statement CREATE DATA or instance operator
NEW). In addition, the literals defined as part of the source code are also data objects.
The data type of a data object is always complete (not generic) and can be bound or
standalone. See also static data object and dynamic data object

Static data object

 A data object for which all attributes, including memory consumption, are specified as
static by the data type. Apart from reference variables, all static data objects are flat.

Dynamic data object

 Data object for which all properties apart from the memory consumption are statically
determined by the data type. Dynamic data objects are strings and internal tables, and are
counted as deep data objects. Structures that contain dynamic components are also
dynamic data objects. All other data objects, with the exception of boxed components are
static data objects. When dynamic data objects are accessed, value semantics apply.
Example

The string template in the method main uses embedded expressions to display the text "Hello
world!". The first embedded expression is the attribute attr of the class. The return value of the
method func is used in the second embedded expression. The third embedded expression is again
the attribute attr, whose value has been changed in the method func in the meantime. The second
embedded expression includes a line break and a comment.

CLASS demo DEFINITION.


PUBLIC SECTION.
CLASS-METHODS: main,
func RETURNING value(p) TYPE string.
PRIVATE SECTION.
CLASS-DATA attr TYPE string VALUE `Hello`.
ENDCLASS.

CLASS demo IMPLEMENTATION.


METHOD main.
DATA txt TYPE string.
txt = |{ attr }{ func( ) "a function
WIDTH = 6 ALIGN = RIGHT }{ attr }|.
MESSAGE txt TYPE 'I'.
ENDMETHOD.
METHOD func.
p = `world`.
attr = '!'.
ENDMETHOD.
ENDCLASS.

START-OF-SELECTION.
demo=>main( ).
Embedded Expressions - format_options: (Standard SAP help)

[WIDTH = len]
[ALIGN = LEFT|RIGHT|CENTER|(val)]
[PAD = c]
[CASE = RAW|UPPER|LOWER|(val)]
[SIGN = LEFT|LEFTPLUS|LEFTSPACE|RIGHT|RIGHTPLUS|RIGHTSPACE|(val)]
[EXPONENT = exp]
[DECIMALS = dec]
[ZERO = YES|NO|(val)]
[XSD = YES|NO|(val)]
[STYLE = SIMPLE|SIGN_AS_POSTFIX|SCALE_PRESERVING
|SCIENTIFIC|SCIENTIFIC_WITH_LEADING_ZERO
|SCALE_PRESERVING_SCIENTIFIC|ENGINEERING
|(val)]
[CURRENCY = cur]
[NUMBER = RAW|USER|ENVIRONMENT|(val)]
[ALPHA = IN|OUT|RAW|(val)]
[DATE = RAW|ISO|USER|ENVIRONMENT|(val)]
[TIME = RAW|ISO|USER|ENVIRONMENT|(val)]
[TIMESTAMP = SPACE|ISO|USER|ENVIRONMENT|(val)]
[TIMEZONE = tz]
[COUNTRY = cty] ...

DATA: ts      TYPE timestampl,
      output  TYPE string,
      output1  TYPE string.

GET TIME STAMP FIELD ts.

output =  |{ ts TIMESTAMP = ISO TIMEZONE = 'UTC   ' }|.
WRITE / output.

output1 =  |{ ts TIMESTAMP = ISO }|.
WRITE / output1.

DATA(result1) = |Hello World!|.
WRITE / result1.
data res TYPE string.

res = |{ RESULT1 CASE = UPPER }|.
WRITE / RES.

DATA(result2) = |Hello| && | | & |World| && |!|.

WRITE / result2.
DATA(result3) = |Hello| & "sub template 1
                | |     &
                |World| & "sub template 3
* sub template 4:
                |!|.

WRITE / result3.
Please find the standard function codes and the corresponding texts...
 
%ML                  Folder                                     
%PC                  Local file...                              
%PC                  Local file...                              
%SC                  Find                                       
%SC+                 Find next                                  
%SL                  Mail recipient                             
%SL                  Mail recipient                             
&ABC                 ABC analysis                               
&ABC                 ABC analysis                               
&ABC                 ABC analysis                               
&ALL                 Select all                                 
&ALL                 Select all                                 
&AQW                 Word processing...                         
&AQW                 Word processing...                         
&AUF                 Define totals dri...                       
&AUF                 Define drilldown...                        
&AUF                 Define totals drilldown...                 
&AVE                 Save...                                    
&AVE                 Save layout...                             
&AVE                 Save layout...                             
&AVR                 Mean value                                 
&CDF                 Unfreeze columns                           
&CFI                 Freeze to column                        
&CRB                 First column                            
&CRDESIG             Crystal Reports D...                    
&CRDESIG             Crystal Reports Designer                
&CRE                 Last column                             
&CRL                 Column left                             
&CRR                 Column right                            
&CRTEMPL             Crystal Reports file                    
&DATA_SAVE           Save                                    
&DAU                 Automatic separator                     
&DOF                 Separator always off                    
&DON                 Separator always on                     
&DQS                 Display Quality R...                    
&EB9                 Call up report...                       
&ELP                 Help                                    
&ERW                 Layout Managemen                        
&ERW                 Layout Management                       
&ETA                 Details                                 
&F03                 Back                                    
&F12                 Cancel                                  
&F15                 Exit                                    
&F4                  Possible entries                        
&GRAPH               Graphic                            
&GRAPH               Graphic                            
&IC1                 Choose                             
&ILD                 Delete filter                      
&ILT                 Set filter                         
&ILT                 Set filter                         
&INFO                Information                        
&KOM                 Choose...                          
&LFO                 List status...                     
&LFO                 List status...                     
&LIS                 Basic list                         
&MAX                 Maximum                            
&MIN                 Minimum                            
&NFO                 Selections...                      
&NTE                 Refresh                            
&OAD                 Choose...                          
&OAD                 Select layout...                   
&OAD                 Select layout...                   
&ODN                 Sort in descendin...               
&ODN                 Sort in descending order           
&OL0                 Change layout...                   
&OLX                 Change...                          
&OMP                 Collapse                  
&OPT                 Optimize width            
&OUP                 Sort in ascending...      
&OUP                 Sort in ascending order   
&REFRESH             Refresh                   
&RNT                 Print                     
&RNT_PREV            Print preview             
&RNT_PREV            Print preview             
&SAL                 Deselect all              
&SAL                 Deselect all              
&SAL                 Deselect all              
&SAV                 Save                      
&SUM                 Subtotals...              
&SUM                 Subtotals...              
&UMC                 Total                     
&UMC                 Total                     
&VCRYSTAL            Crystal Reports           
&VEXCEL              Microsoft Excel           
&VEXCEL              Microsoft Excel           
&VGRID               SAP List Viewer           
&XINT                Extended storage ...      
&XINT                Extended storage of SAP Query     
&XPA                 Expand                            
&XXL                 Spreadsheet...                    
&XXL                 Spreadsheet...                    
CARR                 REDETERMINE CARRIER               
CREA                 CREATE ALLOCATION                 
DESELECT             Deselect All                      
DSCT                 Deselect ALL                      
DSEL                 Deselect all                      
LEGEND               Legend Details                    
LEGEND               Legend Details                    
ONLI                 Online                            
P                    First page                        
P+                   Next Page                         
P+                   Next page                         
P++                  Last Page                         
P++                  Last page                         
P-                   Prev Page                         
P-                   Previous page                     
P                    First Page                        
P                    First page                        
PRINT                F8 Create PDS       
PRNT                 Create PDS          
SALL                 Select all          
SDEL                 Deselect All        
SELA                 Select All          
SELECT               SELECT ALL          
SLCT                 SELECT ALL

In TABLE VBPA (Customer partners data is available)


The filed PARVW IN VBPA STORES THE VALUES LIKE
AG, LF, WE, RE, SP, RG

E1EDKA1     PARVW     Partner function (e.g. sold-to party, ship-to party, ...)     AG     Sold-to party


E1EDKA1     PARVW     Partner function (e.g. sold-to party, ship-to party, ...)     LF     Vendor
E1EDKA1     PARVW     Partner function (e.g. sold-to party, ship-to party, ...)     WE     Ship-to party
E1EDKA1     PARVW     Partner function (e.g. sold-to party, ship-to party, ...)     RE     Bill-to party
E1EDKA1     PARVW     Partner function (e.g. sold-to party, ship-to party, ...)     SP     Carrier
E1EDKA1     PARVW     Partner function (e.g. sold-to party, ship-to party, ...)     RG     Payer
E1EDKA1     PARVW     Partner function (e.g. sold-to party, ship-to party, ...)     EK     Buyer
E1EDKA1     PARVW     Partner function (e.g. sold-to party, ship-to party, ...)     ZM     Responsible employee
E1EDKA1     PARVW     Partner function (e.g. sold-to party, ship-to party, ...)     VR     Representative
E1EDKA1     PARVW     Partner function (e.g. sold-to party, ship-to party, ...)     CC     SPEC2000 customer code
E1EDKA1     PARVW     Partner function (e.g. sold-to party, ship-to party, ...)     BE     Beneficiary
E1EDKA1     PARVW     Partner function (e.g. sold-to party, ship-to party, ...)     PA     Partner for debit memo/direct
debit/bank collection
E1EDKA1     PARVW     Partner function (e.g. sold-to party, ship-to party, ...)     BA     Bank sold-to party
E1EDKA1     PARVW     Partner function (e.g. sold-to party, ship-to party, ...)     BB     Bank beneficiary/partner for
debit memo
E1EDKA1     PARVW     Partner function (e.g. sold-to party, ship-to party, ...)     RS     Invoicing party
E1EDKA1     PARVW     Partner function (e.g. sold-to party, ship-to party, ...)     ME     Declarant
E1EDKA1     PARTN     Partner number          
 

Common questions

Powered by AI

Using 'TRANSLATE' to change the case of strings can significantly impact string comparison operations. Since string comparisons in ABAP are case-sensitive, altering the case of a string using 'TRANSLATE' can change the outcome of such comparisons. For instance, converting all characters to uppercase or lowercase can ensure uniformity, which is critical in scenarios where case-insensitive comparison is needed. Without 'TRANSLATE', two strings differing only by case would not be treated as equal .

Embedded expressions in string templates offer significant benefits by allowing complex data expressions and calculations to be integrated directly into strings, enhancing code readability and flexibility. They enable dynamic content generation, where variable values and expression results can be embedded directly. This reduces the need for additional lines of code to concatenate values or handle complex formatting separately. However, the limitations include the complexity of embedding extensive logic within string templates, which could lead to reduced code clarity if not structured properly. Additionally, the need for correctly managing data types and formats demands careful attention to ABAP syntax rules .

Format options in embedded expressions of string templates are crucial for controlling the output format of data. They allow precise specification of how values should be presented, including width, alignment, padding, case transformation, and more. For example, the expression |{ var CASE = UPPER ALIGN = RIGHT WIDTH = 10 }| ensures the variable 'var' is printed in uppercase, right-aligned, in a 10-character-wide field. This facilitates the creation of formatted output tailored to specific requirements, enhancing clarity and aesthetics .

Escaping special characters in ABAP string templates is essential to differentiate between literal use and syntax, ensuring that special characters such as '|', '{', and '}' are correctly included in the string. This practice maintains code legibility and prevents syntax errors that could arise from misinterpreting these characters as part of the template's syntax. Properly escaped characters also enhance maintenance, as they make the intended string content explicit, reducing the likelihood of errors during updates or refactoring. However, overusing escapes can decrease readability, making it crucial to balance escape usage with code clarity .

The 'REPLACE' function in ABAP is used to replace occurrences of a substring within a string with another substring. This operation directly modifies the original string by substituting all occurrences of the specified substring with the new string. It's useful for standardizing or correcting content within strings, such as replacing specific characters or words across the entire string. Once replaced, the changes are reflected directly in the original string variable .

The 'SPLIT' operation in ABAP is used to split a main string into multiple substrings based on a specified separator. Each resulting substring is then assigned to different variables in the sequence of their order. The effect of this operation is that it allows you to parse a combined input into separate parts for easier handling or further processing, suitable in situations where you need to extract specific parts from a structured input, like CSV data .

Dynamic memory allocation for strings in ABAP allows memory to be used efficiently, as it allocates space based on the content's actual size at runtime. This can lead to performance benefits by minimizing wasted space and allowing more flexible memory use. However, it can also introduce overhead in memory management, as the system needs to allocate and deallocate memory dynamically, which could impact execution speed if not managed carefully. In contrast, static memory allocation, while less flexible and potentially wasteful, is consistent and predictable, avoiding the overhead associated with dynamic allocation .

ABAP uses a variety of operators for string comparison, such as 'CO' (contains only), 'CN' (contains not only), 'CA' (contains any), and 'CP' (matches pattern). Each operator has a specific logic for how strings are compared, which is case-sensitive. A potential pitfall is misunderstanding these operations, such as assuming 'CO' evaluates to true if all characters of string1 are found in string2, leading to incorrect results if not used properly. Additionally, poorly handled case sensitivity and incorrect string pattern expectations can lead to logical errors in program outcomes .

The 'CONCATENATE' operation in ABAP is used to join multiple substrings into one string variable. The syntax involves listing the string elements to be concatenated, followed by the target string variable. The 'SEPARATED BY' clause allows you to specify a separator that will be inserted between the concatenated substrings. This is important for creating readable and properly formatted outputs, where elements need to be distinctly separated by characters like commas or spaces .

The primary difference is that character data types have a fixed memory allocation, meaning that space is allocated based on the declared size, regardless of the actual content size. For instance, if you declare a variable as type char50, 50 characters of memory are allocated, even if you store fewer characters. On the other hand, string data types allocate memory dynamically based on the content's size at runtime, which means that only the necessary amount of memory is used according to the current field content .

String Operations In ABAP (http://sapabap-freshers.blogspot.in/2012/06/string-operations-in-abap.html)
String Operations:
Str
Output:
CONDENSER: replace the sequence of spaces into one space
Ex: CONDENSER ‘Career                it’.
Result: Career it
SPLIT:
 
   to split the main string into substrings at the given separator
SPLIT <String> AT <separator> into <str1> <str2>…
Examples:
•         'AABB' co 'AB' True
•         'ABCD' co 'ABC' False
•         'AABB' cn 'AB' False
•         'ABCD' cn 'A
String Template:
A string  (sapevent:ABENSTRING_EXPRESSION_GLOSRY)template is enclosed between two "|" characters and can onl
String Templates - Literal_text 
Syntax 
c...c 
Effect 
Within a string template |...|, a literal text c...c represents its e
String Templates - embedded_expressions 
Syntax  :
{ expr [format_options (sapevent:ABAPCOMPUTE_STRING_FORMAT_OPTIONS)] } 
Ef
Notes 

Unlike other syntax representations in the ABAP key word documentation, the curly 
brackets are part of the syntax.

You might also like