Loop Though Strings

2019-09-21 02:12发布

I seem to be stuck trying to loop through strings to find characters that are not in the other string. The goal of the program is to loop though string one and document the characters that are not in the other string. The characters that are not in the other string will be printed out after all the checking is finished. They may not be repeated, hence I attempt to use three loops.

I am trying to debug the code below, since I have to eventually check both strings against each other, and I want to do this manually for the know how.

CG-USER(258): (defun stringprod (string1 string2) 
(let ((newString nil))
(let ((letterSearchOn nil))
(loop for i from 0 below (length string1)
    always
    (setf (letterSearchOn (char string1 i))           
         (loop for j from 0 below (length string2)            
             (for ch =  (char string2 j)
             (/when (find ch letterSearchOn :test #'equal)
             (append newString ch)))))))))
STRINGPROD
CG-USER(260): (stringprod "abc" "abc")
Error: (FOR CH = (CHAR STRING2 J)
    (/WHEN (FIND CH LETTERSEARCHON :TEST #'EQUAL)
     (APPEND NEWSTRING CH))) found where LOOP keyword expected.
Current LOOP context: FOR J FROM 0 BELOW (LENGTH STRING2)
   (FOR CH = (CHAR STRING2 J)
    (/WHEN (FIND CH LETTERSEARCHON :TEST #'EQUAL) (APPEND NEWSTRING CH))).
[condition type: PROGRAM-ERROR]
CG-USER(261): 

2条回答
ゆ 、 Hurt°
2楼-- · 2019-09-21 02:25

You need to check the syntax of LOOP: http://www.lispworks.com/documentation/HyperSpec/Body/m_loop.htm

(loop for i from start1
      for j from start2
      do ...)

Your code has added parentheses, missing do words and weird characters like /.

If your question is homework, you should tag it as such. If not you can use SET-DIFFERENCE.

(set-difference (coerce "abc" 'list) (coerce "bcd" 'list))
-> (#\a)
查看更多
ゆ 、 Hurt°
3楼-- · 2019-09-21 02:29

How about something like this?

(defun remove-unsafe (str unsafe)
  (remove-duplicates
   (remove-if #'(lambda (c) (find c unsafe)) str)))
查看更多
登录 后发表回答