From Scriptwiki
Jump to: navigation, search

Inserts token into the Nth position in text, even if it already exists in text.


Note that you can specify a negative value for N.


var %mytext This is my text
var %mynewtext = $instok(%mytext, new, 4, 32)
echo -a %mynewtext 

This example would return This is my new text, as new was inserted in the 4th position.

The following example is a little bit more complex. It's about adding a number in a string in the correct position (e.g. sorting (insertsort))

 var %mynumbers = 1,4,8,34,77,111,876
 var %mynewnumber = 77
 ; set %numbers to the count of numbers in %mynumbers
 var %i = 1, %numbers = $numtok(%mynumbers,44)
 while (%i <= %numbers) {
   ; check if the number at position %i is bigger than %mynewnumber
   if ($gettok(%mynumbers,%i,44) > %mynewnumber) {
     ; it is bigger, so put it at this position
     var %mynumbers = $instok(%mynumbers,%mynewnumber, %i, 44)
     ; stop the while loop, as we are done.
   inc %i
   ; if we are at the end, the number is obviously not inserted. Put it at the end, as it is bigger than every other.
   if (%i == %numbers) {
     var %mynumbers = $instok(%mynumbers,%mynewnumber, $calc(%i + 1), 44)
 ; echo the new string
 echo -a %mynumbers