ReplaceString and a new SelectString

With function ConvertStr you can replace substrings in strings. The original substring and the replacement have to have the same length. So what to do, if the length is different? Here is a solution.

ReplaceString(String : Text[250];OrigSubStr : Text[100];ReplSubStr : Text[100]) : Text[250]
// StartPos : Integer
StartPos := STRPOS(String,OrigSubStr);
WHILE StartPos > 0 DO BEGIN
  String := DELSTR(String,StartPos) + ReplSubStr + COPYSTR(String,StartPos + STRLEN(OrigSubStr));
  StartPos := STRPOS(String,OrigSubStr);
END;
EXIT(String);

SelectStr is a nice function to get text values out of a text line, simply giving the number/position of the value within the line, e.g. from ‘this,was,a,cool,thing’. here ‘was’ has position 2, so selectstr(2,line) would give us value ‘was’. SelectStr expects a comma as delimiter. Not so good, if you also have comma letters in the values (e.g. decimal values in europe). Would be fine to have a kind of SelectString function, where you can define the delimiter. hm … let’s try something.

SelectString(Number : Integer;String : Text[250];Delimiter : Char) : Text[100]
// i : Integer
// EndPos : Integer
// SubString : Text[100]
i := 1; // i : Integer
WHILE i  0 THEN BEGIN
    SubString := COPYSTR(String,1,EndPos-1);
    String := DELSTR(String,1,EndPos);
  END ELSE
    SubString := String;
END;
EXIT(SubString);

To test that new function we use that:

// line : Text[250]
// i : Integer
line := 'ab;cd;ef;cd';
for i := 1 to 4 do
  MESSAGE(SelectString(i,line,';'));

cheers

 

Advertisements

3 thoughts on “ReplaceString and a new SelectString

  1. Hi Archer,

    It’s a good read. For replacing strings, you can use the .NET component and with 3 lines of code, it handles all complexity behind. Check out:

    PROCEDURE Replace@4(String@1000 : Text;OldValue@1001 : Text;NewValue@1002 : Text) : Text;
    VAR
    DotNetString@1003 : DotNet “‘mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089’.System.String”;
    BEGIN
    DotNetString := String;
    DotNetString := DotNetString.Replace(OldValue, NewValue);
    EXIT(FORMAT(DotNetString));
    END;

    Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s