; move spaces to front
(define (spaces-to-front str)
(define (swap! a b)
(let ((temp (string-ref str a)))
(string-set! str a (string-ref str b))
(string-set! str b temp)))
(let ((len (- (string-length str) 1)))
(let loop ((i len) (j len))
(cond ((negative? i)
(do ((j j (- j 1)))
((negative? j) str)
(string-set! str j #\space)))
((char=? #\space (string-ref str i))
(loop (- i 1) j))
(else (swap! i j) (loop (- i 1) (- j 1)))))))
(display (spaces-to-front "h e l l o")) (newline)
(display (spaces-to-front "hello ")) (newline)
(display (spaces-to-front " hello")) (newline)
(define (spaces-to-front str)
(define (swap! a b)
(let ((temp (string-ref str a)))
(string-set! str a (string-ref str b))
(string-set! str b temp)))
(set! str (string-append str (string #\nul)))
(let loop ((i 0) (j 0))
(cond ((char=? (string-ref str j) #\nul) str)
((char=? (string-ref str j) #\space)
(swap! i j) (loop (+ i 1) (+ j 1)))
(else (loop i (+ j 1))))))
(display (spaces-to-front "h e l l o")) (newline)
(display (spaces-to-front "hello ")) (newline)
(display (spaces-to-front " hello")) (newline)