Discuss and learn Lisp programming of all dialects
This is a read-only archive of lispforum.com. The forum was locked to new users and
posts and is preserved here as static HTML from a database snapshot taken on
2019-09-07.
What do you mean by translation? Common Lisp is, unlike C, a strongly typed language with, usually, automatic memory management. They are too different for there to be any direct correspondence.
One big difference between C strings and Lisp strings is that the former use a null byte to mark end-of-string while the latter store an explicit length. Anyway, here's some code to chew over. Note that t is a predefined symbol in the CL package; thus its usually easier to use a different name than to shadow it in another package.
(defun strcmp-i (str1 str2)
"one approach towards implementing strcmp_i (incomplete)"
;; returns the index of the first character which was not the same
;; could be used below instead of string-not-equal
(loop for c1 across str1
and c2 across str2
and i = 1 then (1+ i)
while (char= c1 c2)
finally (return i))
1)
(defun strcmp-i2 (str1 str2)
"a more idiomatic strcmp_i (complete)"
(let ((index (string-not-equal str1 str2)))
(cond ((not index)
0)
((= index (length str1))
-1)
((= index (length str2))
1)
(t (- (char-code (char str1 index))
(char-code (char str2 index)))))))
hi Ramarren,
Than you for the reply.
I mean converting strcmp(), such that,
(strcmp 'abc 'abbbe) => 1 : here last character (3rd character = c) in 'abc is greater than b(3rd character) in 'abbbe so => 1.
(strcmp 'abc 'abcd) => -1 : here the null character in 'abc is inferious to d(4rd character) in 'abcd so => -1.
(strcmp 'abc 'abc) => 0 : here the last characters are equal so => 0.
I just wanted to chime in that common lisp has a few routines for string-comparison (e.g. string-equal and string<). Just making sure you're porting strcmp for practice and not necessity.
Need an online wiki database? My Lisp startup http://www.formlis.com combines a wiki with forms and reports.