Split String

Hi everybody

Does anyone know how to do string split in NAV.

I’ve a string like ‘ABC-111-124’ and i want to split it like string1:=ABC

string2:=111 and string3:=124


There are numerous way to do this with code:

Here is 1 way:

AString := ‘ABC-111-124’;
workString := CONVERTSTR(AString,’-’,’,’);
String1 := SELECTSTR(1,workString);
String2 := SELECTSTR(2,workString);
String3 := SELECTSTR(3,workString);

MESSAGE(‘Original String %1\String 1 = %2\String 2 = %3\String 3 = %4’,AString,String1,String2,String3);

hehhh… nice solution if you freely suppose that your string doesn’t already containes commas.
However, if it does than you cannot do what you want unless you have some other “supposes” like one that string is always in same format XXX-XX-XXX (e.g.)

Though, it is rarity to have such strings (with commas included as values, not as separator in csvs) I’m kind of willing not to suppose anything but rather to avoid it with pre-checks.

thanks for helping me

it works fine when the string looks like ‘abc-111-111’

but i’ve a problem when it looks like ‘abc–111’…

SELECTSTR(3,workString) means:

“give me the third (3) which is separeted by commas”.

but you don’t have that third string, you have only one separator => two strings, so it gives you an error.
check the number of strings (actually, the number of separators) before extract.

Here my two cents:

Create a function in a codeunit to reuse from different places:

“Pos” is a local integer variable
Token(VAR Text : Text[1024];Separator : Text[1]) Token : Text[1024]

Pos := STRPOS(Text,Separator);
Token := COPYSTR(Text,1,Pos-1);
IF Pos+1 <= STRLEN(Text) THEN
Text := COPYSTR(Text,Pos+1)
Text := ‘’;
Token := Text;
Text := ‘’;

Then call the code like this:

string := ‘ABC-111-124’;

Part1 := Token(string,’-’); // Returns ‘ABC’ and changes string to ‘111-124’
Part2 := Token(string,’-’); // Returns ‘111’ and changes string to ‘124’
Part3 := Token(string,’-’); // Returns ‘124’ and changes string to ‘’

Yes, yes… ofcourse you need to introduce error checking etc, else you will quickly get problems with strings like “xxx–xxx”… it was a simple answer to a simple question [;)]

thanks for your help!

the codeunit works perfect :slight_smile:

Always glad to help