Sunday, May 28, 2017

Reverse STRPOS in Microsoft Dynamics NAV

dynamics nav 2016

Hello everybody, this is my first blog. In this blog I would like to share a useful function that when you need to search for the first occurrence of substring inside a string from the right. Of cause, Microsoft Dynamics NAV has the function but you can use only from the left (that function is STRPOS). I name this function RSTRPOS (Reverse STRPOS), so let’s start with the example
Position := RSTRPOS(String, SubString)

The function needs two parameters (text). One is the string in which you want to search. The other is the substring for which you want to search from the right of string. The result of the function returns the first position of Substring in String from the right as integer.
If String is empty or Substring cannot be found or empty, then the function returns zero.

Example

Declare the following variables:

Text Constant  
ENU Value
Text000 
                                             C:\temp\myFile\NAV
Text001
\

The message window display: 15

Now let’s see the code


Documentation

Parameters
String
Type: Text constant or code
The string in which you want to search.
SubString
Type: Text constant or code
The substring for which you want to search from the right of string.
The RSTRPOS function is case-sensitive

Return Value
Type: Integer
The first position of SubString in String from the right.

Remark
The RSTRPOS function returns the position of the first right occurrence of the substring
If SubString cannot be found, then the function return zero.
If String or Subtring is empty, then the function returns zero.

4 comments:

  1. This function only supports substrings of length 1, yes? A modification for longer substrings could be:

    LOCAL RSTRPOS(String_par : Text;Substring_par : Text) : Integer
    IF (String_par = '') OR
    (Substring_par = '')
    THEN
    EXIT(0);

    String_loc := String_par;
    StrLenSubstring_loc := STRLEN(Substring_par);

    WHILE STRLEN(String_loc) >= StrLenSubstring_loc DO BEGIN
    SearchPosition_loc := STRLEN(String_loc) - StrLenSubstring_loc + 1;
    IF SearchPosition_loc < 1 THEN
    EXIT(0);
    SearchString_loc := COPYSTR(String_loc,SearchPosition_loc,StrLenSubstring_loc);

    IF SearchString_loc = Substring_par THEN
    EXIT(SearchPosition_loc);

    String_loc := COPYSTR(String_loc,1,STRLEN(String_loc)-1);

    END;

    EXIT(0);

    ReplyDelete
  2. input: '01.01.02.'
    output: '01.01.'

    input: '01.02.03.04.'
    output: '01.02.03.'

    input: '01.'
    output: ''

    local procedure GetParentPosition(Pos: Text; Sep: Text): Text
    var
    i: Integer;
    begin
    i := StrPos(Pos, '.');
    if i = 0 then
    exit;
    EXIT(COPYSTR(pos, 1, STRLEN(pos) - STRPOS(COPYSTR(pos, 1, i), sep)));
    end;

    ReplyDelete

Powered by Blogger.

About me

Popular Posts

Adbox