How to join two utf8 strings together in Clarity?

143 views Asked by At

In my Clarity smart contract, I am trying to to append one string ("Hello") to another string (" to Clarity Language"). Both strings are of type string-utf8.

Deploying the contract below fails with an error: expecting expression of type \'(string-utf8 100)\', found \'(string-utf8 120)\'

(define-data-var a-string (string-utf8 100) u"Hello")

(var-set a-string (concat (var-get a-string) u" to Clarity Language"))
(print (var-get a-string))

How to make this work?

1

There are 1 answers

0
friedger On

concat does not optimize the resulting string. The new string is of type string-utf8 with length 120, adding the length of the variable type to the length of the other string (100 + 20).

You have to wrap the concat call with a as-max-len?:

(define-data-var a-string (string-utf8 100) u"Hello")

(var-set a-string 
  (unwrap! (as-max-len? 
    (concat (var-get a-string) u" to Clarity Language") u100) (err "text too long")))
(print (var-get a-string))

Note, that the type length is defined by an int (100), while as-max-len? takes a uint parameter (u100).