Como substituir uma substring dentro de uma string?

O comando INSPECT com a opção REPLACING pode ser usado para substituir uma substring dentro de uma string.

O programa abaixo troca todos os caracteres “!” por “;”:

identification division.
program-id. gtc004.

data division.
working-storage section.
01 wt-string pic x(100) 
    value "JOAO DA SILVA!RUA FRAZE 90!PARQUE DO IMBUI!TERESOPOLIS!RJ".

procedure division.
inicio.
    display "Antes : " wt-string
    inspect wt-string replacing all "!" by ";"
    display "Depois: " wt-string
    stop run.

E quando executado mostra o seguintes resultado:

[aeisxpad ~/cbl]$ gtc004
Antes : JOAO DA SILVA!RUA FRAZE 90!PARQUE DO IMBUI!TERESOPOLIS!RJ
Depois: JOAO DA SILVA;RUA FRAZE 90;PARQUE DO IMBUI;TERESOPOLIS;RJ

Uma restrição do comando INSPECT é que o tamanho das substrings (“!” e “;”) precisam ter o mesmo tamanho. Você não pode substituir “!” por “;;;” por exemplo. Para fazer isso uma das opções seria usar a função intrínseca SUBSTITUTE, se estiver disponível no seu compilador.

identification division.
program-id. gtc004.

environment division.
configuration section.
repository.
    function all intrinsic.

data division.
working-storage section.
01 wt-string pic x(100) 
    value "JOAO DA SILVA!RUA FRAZE 90!PARQUE DO IMBUI!TERESOPOLIS!RJ".

procedure division.
inicio.
    display "Antes : " wt-string
    move substitute(wt-string, "!", ";;;") to wt-string
    display "Depois: " wt-string
    stop run.

[aeisxpad ~/cbl]$ gtc004
Antes : JOAO DA SILVA!RUA FRAZE 90!PARQUE DO IMBUI!TERESOPOLIS!RJ
Depois: JOAO DA SILVA;;;RUA FRAZE 90;;;PARQUE DO IMBUI;;;TERESOPOLIS;;;RJ

Deixe uma resposta

O seu endereço de e-mail não será publicado. Campos obrigatórios são marcados com *