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.

C's strcmp to CLISP

7 posts · 1730 views

Hi all,
could anyone help me out with the translation of C's strcmp() to CLISP.
C source:
int strcmp_i(char *s, char *t)
{
	for(; *s==*t && *s!='\0'; s,t);
	return(*s - *t);
}
Thanks a lot.

Last edited by nuntius on , edited 1 time in total. Reason: add code tag

Re: C's strcmp to CLISP

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.

Re: C's strcmp to CLISP

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)))))))

Re: C's strcmp to CLISP

Thank you nuntius ,Your code snippet seems to solve the problem, I will go through it carefully, and see how I could implement it recursively.

Thank you again.

Re: C's strcmp to CLISP

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.


Thank you.

Re: C's strcmp to CLISP

Note that 'abc is not a string in Lisp, it is a symbol. The denotation of strings in Lisp is between quotes, "abc".

If you want to work with symbols, convert them to strings using symbol-name.

Re: C's strcmp to CLISP

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.