To find the length of character strings ABAP function STRLEN is used. This function returns the length of the string counting till the last character that is not a space. Please note that if you try to compute the length of a sentence like 'This is a sentence' then the length of the complete sentence is calculated ie 18. Consider the word 'FUNCTION ' in this example there are 2 spaces after the word FUNCTION but the STRLEN function will consider the length only for the word FUNCTION ie 8. If you put spaces preceding the word then the spaces are also counted for example ' SPACES' the length of this will be counted as 16.
In cases where you want to count just the number of characters it is better to use CONDENSE with the addition of NO-GAPS on field variable before using STRLEN.
CONDENSE statement is used to delete unwanted leading spaces in strings. To remove all the space even those between words use CONDENSE with NO-GAPS.
Example.
DATA: INT TYPE I, WORD1(20) VALUE '12345', WORD2(20), WORD3(20) VALUE ' 4', WORD4(20) VALUE ' ABCD EFGH', WORD5(20) VALUE 'ABCD ', WORD6(20) VALUE 'ABCD EFGH IJKL'.
INT = STRLEN( WORD1 ). WRITE INT.
INT = STRLEN( WORD2 ). WRITE / INT.
INT = STRLEN( WORD3 ). WRITE / INT.
INT = STRLEN( WORD4 ). WRITE / INT.
INT = STRLEN( WORD5 ). WRITE / INT.
INT = STRLEN( WORD6 ). WRITE / INT.
The output of the above program will be as follows.
String Length 5 0 7 10 4 14
In cases where you want to find the exact length of the the characters you can use CONDENSEwith the addition of NO-GAPS before finding the length. Please see the examples given below. Note that CONDENSE without the addition of NO-GAPS will remove only the leading spaces.
DATA: CHK_LEN(25) VALUE ' one two three four', LEN TYPE I.
* Will remove the leading and trailing spaces. CONDENSE CHK_LEN. LEN = STRLEN( CHK_LEN ). WRITE: CHK_LEN, '!'. WRITE: / 'Length: ', LEN.
* Will remove the spaces between the words as NO-GAPS is used CONDENSE CHK_LEN NO-GAPS. LEN = STRLEN( CHK_LEN ). WRITE: CHK_LEN, '!'. WRITE: / 'Length: ', LEN.
The output of the above program will be as follows.
Example on Condesne one two three four ! Length: 19 one two three four ! Length: 18 onetwothreefour ! Length: 15
Always use Pretty Printer and Extended Program Check before releasing the code.
Do not leave unused code in the program. Comment the code thoroughly. Align the comments and the Code. Follow the SAP Standards and SAP Best Practices guidelines. It’s a good practice to take a dump of the code on your local drive.
No comments:
Post a Comment