Question

I need to remove a character from a string, but I can't figure out how to specify a count, that is a limit on how many times said character should be removed from string in Chicken.

Here's how I'd do it in Common Lisp:

(let ((a "abca")) (delete #\a a :count 1))

;=> "bca"

How would I do that in Chicken-scheme?

I've tried using delete in Chicken, but Chicken's delete doesn't seem to support a count thingy thing, so the following does not work:

(let ((a "abca")) (list->string (delete #\a (string->list a) :count 1)) ))

And just running delete on a string removes all occurrences of char:

(let ((a "abca")) (list->string (delete #\a (string->list a)) ))

;=> "bc"
Was it helpful?

Solution

(define myfilter
  (lambda (lst char cnt)
    (if (null? lst)
      '() 
      (if (and (eq? (car lst) char) (> cnt 0)) 
        (myfilter (cdr lst) char (- cnt 1)) 
        (cons (car lst) (myfilter (cdr lst) char cnt))))))

(define delnchars
  (lambda (str char count)
    (list->string (myfilter (string->list str) char count))))

> (delnchars "3 i's will be removed, the last -> is here" #\i 3)
"3 's wll be removed, the last -> s here"
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top