ayahya82
ayahya82

Reputation: 386

Looping string characters?

How can I read each character in a String? For example, I want to read each character in String "a7m4d0". After that I want to verify that each character is a character or a number. Any tips or ideas?

Upvotes: 3

Views: 78238

Answers (5)

Alejandro Mayorga
Alejandro Mayorga

Reputation: 123

I know the post it's old but this might be useful, this is what use :)

  DATA lv_counter TYPE i.

  DO STRLEN( lv_word ) TIMES.

    IF lv_word+lv_counter(1) CA '0123456789'
      "It's a number 
    ENDIF.

    lv_counter = lv_counter + 1.

  ENDDO.

Upvotes: 0

tomdemuyt
tomdemuyt

Reputation: 4592

One more approach

PERFORM analyze_string USING `qwert1yua22sd123bnm,`.

FORM analyze_string USING VALUE(p_string) TYPE string.

  WHILE p_string IS NOT INITIAL.
    IF p_string(1) CA '0123456798'.
      WRITE: /  p_string(1) , 'was a number'.
    ELSE.
      WRITE: /  p_string(1) , 'was no number'.
    ENDIF.
    p_string = p_string+1.
  ENDWHILE.

ENDFORM.

No DATA statements, string functions or explicit indexing required.

Upvotes: 2

Guillaume
Guillaume

Reputation: 277

A bit convoluted and on a recent 740 ABAP server. :)

DATA: lv_text  TYPE string  VALUE `a7m4d0`.

DO strlen( lv_text ) TIMES.
  DATA(lv_single) = substring( val = lv_text off = sy-index - 1 len = 1 ) && ` is ` &&
                    COND string( WHEN substring( val = lv_text off = sy-index - 1 len = 1 ) CO '0123456789' THEN 'Numeric'
                                 ELSE                                                                             'Character' ).
  WRITE : / lv_single.
ENDDO.

Upvotes: 7

vlad-ardelean
vlad-ardelean

Reputation: 7622

DATA: smth TYPE string VALUE `qwert1yua22sd123bnm,`,
      index TYPE i,
      length TYPE i,
      char  TYPE c,
      num   TYPE i.

length = STRLEN( smth ).

WHILE index < length.
  char = smth+index(1).
  TRY .
      num = char.
      WRITE: / num,'was a number'.
    CATCH cx_sy_conversion_no_number.
      WRITE: / char,'was no number'.
  ENDTRY.
  ADD 1 TO index.
ENDWHILE.

Here's your problem solved :P

Upvotes: 12

Tim Radcliffe
Tim Radcliffe

Reputation: 1883

Here is how you can access a single character within a string:

This example will extract out the character "t" into the variable "lv_char1".

DATA: lv_string TYPE char10,
      lv_char   TYPE char1.

lv_string = "Something";

lv_char1 = lv_string+4(1).

Appending "+4" to the string name specifies the offset from the start of the string (in this case 4), and "(1)" specifies the number of characters to pick up.

See the documentation here for more info:

http://help.sap.com/saphelp_nw04/Helpdata/EN/fc/eb341a358411d1829f0000e829fbfe/content.htm

If you want to look at each character in turn, you could get the length of the field using "strlen( )" and do a loop for each character.

Upvotes: 3

Related Questions