Q:

Xquery Split a string by the Nth occurrence of a character

I need some help with splitting a long string of characters by the Nth occurrence of a certain character. For example
<string>1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27</string>

to be split by the 9th comma 
and to become
<string>1,2,3,4,5,6,7,8,9</string>
<string>10,11,12,13,14,15,16,17,18</string>
<string>19,20,21,22,23,24,25,26,27</string>

The length of the original string is not specified and the numbers 1-27 in the example could be words with spaces, but the comma is uniquely a separator.
Thanks!

A:

let $s := <string>1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27</string>
let $len := 9
let $tokens := tokenize($s, ',')
for $n in (1 to count($tokens) idiv $len)
return <string>{ 
  string-join(subsequence($tokens, $len * ($n - 1) + 1, $len), ',') 
}</string>

