Removing characters from a string in Nyquist

1.3k views Asked by At

How can I remove a certain character from a string in Nyquist (which is very similar to xlisp) and have the result returned?

I want to count how many "A" there are in a string like "ABBAAAABBBAABAAAB". (Yes, there are only 'A's and 'B's in the string.)

Since there is no (count) function in Nyquist I tried something like

(length (remove #\B mystring))

or

(length (remove #\B mystring :test equal))

But it doesn't work.

Forgetting the character count for a moment, how can I remove the 'B's from the string?

2

There are 2 answers

6
Inaimathi On BEST ANSWER

Will there always be only As and Bs in the string? If not, you might want to do something like

(remove #\A yourstring :test-not 'char=)

According to the XLISP reference for remove, the Nyquist remove doesn't deal with strings, only lists. You need to convert a string to a list in order to operate on it this way, but there's no coerce either. It's a touch hacky, but the easiest way around it I see is to stream a string and read-char it. This will produce a list of chars that you can then manipulate with remove.

(defun string->list (a-string)
  (let ((collector nil)
        (stream (make-string-input-stream a-string)))
    (dotimes (c (length a-string) (reverse collector))
      (setf collector (cons (read-char stream) collector)))))

It should now be possible to

(remove #\A (string->list yourstring) :test-not 'char=)
0
Steve Daulton On

I see this is an old question, but since it has over 800 views, it's perhaps worth having the simple answer:

(defun remove-char (character sequence)
  (let ((out ""))
    (dotimes (i (length sequence) out)
      (setf ch (char sequence i))
      (unless (char= ch character)
        (setf out (format nil "~a~a" out ch))))))

(setf mystring "ABBAABABCCCCBBCCCCAAA")
(remove-char #\B mystring) ;returns "AAAACCCCCCCCAAA"