Hi, Readers.
Today I would like to share another mini tip about Business Central, how to reverse a string in AL. For example, the user want to reverse the name of the customer, Adatum Corporation -> noitaroproC mutadA.
In this blog, I’ve summarized three easy ways to do this, and you can choose the one you prefer.
1. Using List Data Type
There is a very convenient method in List Data Type.
List.Reverse() Method: Reverses the order of the elements in the entire List.
For example,
PS: Business Central 2023 wave 1 (BC22): Iterating with foreach on Text variables
Source code: Github
pageextension 50125 CustomerListExt extends "Customer List"
{
actions
{
addafter(Email)
{
action(ReverseSelectedCustomerName)
{
Caption = 'Reverse Customer Name';
Image = ReverseRegister;
ApplicationArea = All;
Promoted = true;
PromotedCategory = Process;
PromotedIsBig = true;
trigger OnAction()
var
StringList: List of [Text];
StringLetter: Text;
ReversedString: Text;
begin
ReversedString := '';
foreach StringLetter in Rec.Name do
StringList.Add(StringLetter);
StringList.Reverse();
foreach StringLetter in StringList do
ReversedString += StringLetter;
Message(ReversedString);
end;
}
}
}
}
2. Using indexing with []
We can used the method below, [] to convert the string into a single-dimensional array. What was obtained was a number (Character Code).
Rec.Name[i]
More details: How to extract characters from a string (indexing with []).
For exmaple,
Source code: Github
pageextension 50125 CustomerListExt extends "Customer List"
{
actions
{
addafter(Email)
{
action(ReverseSelectedCustomerName)
{
Caption = 'Reverse Customer Name';
Image = ReverseRegister;
ApplicationArea = All;
Promoted = true;
PromotedCategory = Process;
PromotedIsBig = true;
trigger OnAction()
var
ReversedString: Text;
i: Integer;
j: Integer;
begin
j := 0;
for i := StrLen(Rec.Name) downto 1 do begin
j += 1;
ReversedString[j] := Rec.Name[i];
end;
Message(ReversedString);
end;
}
}
}
}
3. Using Text.CopyStr(Text, Integer [, Integer]) Method
Source code: Github
pageextension 50125 CustomerListExt extends "Customer List"
{
actions
{
addafter(Email)
{
action(ReverseSelectedCustomerName)
{
Caption = 'Reverse Customer Name';
Image = ReverseRegister;
ApplicationArea = All;
Promoted = true;
PromotedCategory = Process;
PromotedIsBig = true;
trigger OnAction()
var
ReversedString: Text;
i: Integer;
begin
for i := StrLen(Rec.Name) downto 1 do
ReversedString += CopyStr(Rec.Name, i, 1);
Message(ReversedString);
end;
}
}
}
}
Very simple, give it a try!!!😁
END
Hope this will help.
Thanks for reading.
ZHU
コメント