Dynamics 365 Business Central: How to extract characters from a string (indexing with [])

Dynamics 365 Business Central

Hi, Readers.
Today I would like to share another mini tip about Business Central, how to extract characters from a string.

For example, we want to know what the fourth letter of a customer’s name is, or want to add a space between each character. How to do it? Of course, we can use String Functions to deal with it, combining some methods can also solve this problem. More details: How to use String Functions in AL (StrPos, CopyStr, PadStr, StrLen, LowerCase, SelectStr…). But is there an easier way to do this?

In this post, I want to introduce another interesting way, we can apply indexing with []. Let us first look at two detailed examples.

Get the fourth letter of a customer’s name:

Add a space between each character:

Or display each character vertically in a message window.

How is this done? As you may have noticed, I used the method below.

Rec.Name[i]

Using this [], you can convert the string into a single-dimensional array (starting from 1). But what was obtained was a number.
For exmaple,

Adatum Corporation:
65 100 97 116 117 109 32 67 111 114 112 111 114 97 116 105 111 110

They are ASCII Characters. Here are some examples I found in the MS Learn (Docs).
character set (0 – 127): 7 bit

CodeCharacterCodeCharacterCodeCharacterCodeCharacter
032[space]64@96`
133!65A97a
23466B98b
335#67C99c
436$68D100d
537%69E101e
638&70F102f
73971G103g
8* *40(72H104h
9* *41)73I105i
10* *42*74J106j
1143+75K107k
1244,76L108l
13* *4577M109m
1446.78N110n
1547/79O111o
1648080P112p
1749181Q113q
1850282R114r
1951383S115s
2052484T116t
2153585U117u
2254686V118v
2355787W119w
2456888X120x
2557989Y121y
2658:90Z122z
2759;91[123{
2860<92\124|
2961=93]125}
3062>94^126~
3163?95_127

Then you can simply convert the ASCII Characters back using the Char Data Type. We have briefly discussed similar processing in How to get the next or previous letter in the alphabet.

That’s all.
This also works for string variables such as Code data type and Text data type.

But if it is used in Integer data type and Decimal data type, the following error will be prompted.

Cannot apply indexing with [] to an expression of type ‘Integer’ALAL0143

In addition to common letters and numbers, other special characters, including emoji, Hiragana or kanji, can also be obtained.

Give it a try!!!😁

PS: Business Central 2023 wave 1 (BC22): Iterating with foreach on Text variables

END

Hope this will help.

Thanks for reading.

ZHU

コメント

Copied title and URL