fork download
  1. ; move spaces to front
  2.  
  3. (define (spaces-to-front str)
  4. (define (swap! a b)
  5. (let ((temp (string-ref str a)))
  6. (string-set! str a (string-ref str b))
  7. (string-set! str b temp)))
  8. (let ((len (- (string-length str) 1)))
  9. (let loop ((i len) (j len))
  10. (cond ((negative? i)
  11. (do ((j j (- j 1)))
  12. ((negative? j) str)
  13. (string-set! str j #\space)))
  14. ((char=? #\space (string-ref str i))
  15. (loop (- i 1) j))
  16. (else (swap! i j) (loop (- i 1) (- j 1)))))))
  17.  
  18. (display (spaces-to-front "h e l l o")) (newline)
  19. (display (spaces-to-front "hello ")) (newline)
  20. (display (spaces-to-front " hello")) (newline)
  21.  
  22. (define (spaces-to-front str)
  23. (define (swap! a b)
  24. (let ((temp (string-ref str a)))
  25. (string-set! str a (string-ref str b))
  26. (string-set! str b temp)))
  27. (set! str (string-append str (string #\nul)))
  28. (let loop ((i 0) (j 0))
  29. (cond ((char=? (string-ref str j) #\nul) str)
  30. ((char=? (string-ref str j) #\space)
  31. (swap! i j) (loop (+ i 1) (+ j 1)))
  32. (else (loop i (+ j 1))))))
  33.  
  34. (display (spaces-to-front "h e l l o")) (newline)
  35. (display (spaces-to-front "hello ")) (newline)
  36. (display (spaces-to-front " hello")) (newline)
Success #stdin #stdout 0s 42848KB
stdin
Standard input is empty
stdout
    hello
    hello
    hello
    lelho
    ohell
    hello