Author Topic: Equivalent of PB REPLACE command  (Read 1357 times)

0 Members and 1 Guest are viewing this topic.

chrisc

  • Guest
Equivalent of PB REPLACE command
« on: March 23, 2018, 09:57:51 AM »
in PB, we have a REPLACE command which according to  http://www.manmrk.net/tutorials/basic/PowerBASIC/pbcc/replace_statement.htm

              replace all occurrences of one string with another string

for example
Code: [Select]
A$ = "abacadabra"

'now replace "bac" with "----bac----"

REPLACE "bac" WITH "----bac----" IN A$

A$ = "abacadabra"

'now replace all "b", "a", and "c" with "*"

REPLACE ANY "bac" WITH "***" IN A$


 is there an equivalent command in O2 ?



Charles Pegge

  • Guest
Re: Equivalent of PB REPLACE command
« Reply #1 on: March 23, 2018, 11:09:36 AM »
Chris,

These are not optimised but they have the functionality

Code: [Select]
'2018-03-23 T 18:25:04
'REPLACE / REPLACE ANY
'
sub replace(byref s as string,byval w as string, byval r as string)
'==================================================================
  '
  dim as sys a,lw,lr
  '
  lw=len(w) : if lw=0 then exit sub
  lr=len(r)
  do
    a=instr(a+1,s,w)
    if a=0 then
      exit do
    else
      s=left(s,a-1)+r+mid(s,a+lw)
    end if
    a=lr+a-1
  loop
end sub


sub replaceAny(byref s as string,byval w as string, byval r as string)
'=====================================================================
  '
  dim as sys a,b,c,i,j,lw,lr,ls
  dim as string ch
  '
  lw=len(w) : if lw=0 then exit sub
  lr=len(r)
  ls=len(s)
  i=1
  do
    if i>lw then exit do
    b=asc(w,i)
    ch=mid(r,i,1)
    j=1
    do
      if j>ls then exit do
      a=asc(s,j)
      if a=b then mid(s,j)=ch
      j+=1
    loop
    i+=1
  loop
end sub

'TESTS
====

s="abcdefabcdef"
replace s,"abc","ABC"
print s 'ABCdefABCdef'

replaceAny s,"fed","FED"
print s 'ABCDEFABCDEF'

Aurel

  • Guest
Re: Equivalent of PB REPLACE command
« Reply #2 on: March 23, 2018, 11:23:07 AM »
hi
this one is also from Charles but i don't know when

Code: [Select]
Function Replace(string t,w,r) as string
  '=======================================
  '
  sys a,b,lw,lr
  string s=t
  '
  lw=Len(w)
  lr=Len(r)
  a=1
  ' 
  do
    a=Instr(a,s,w)
    If a=0 then exit do
    s=Left(s,a-1)+r+Mid(s,a+lw)
    a+=lr
  End do
  Return s
End Function

chrisc

  • Guest
Re: Equivalent of PB REPLACE command
« Reply #3 on: March 24, 2018, 11:44:03 AM »
Thanxx both of you
i will test out these functions  this weekend and tell you my results