Concatenate strings

Concatenate strings

gcsjlewis
Collaborator Collaborator
3,488 Views
4 Replies
Message 1 of 5

Concatenate strings

gcsjlewis
Collaborator
Collaborator

Using Autocad Electrical 2020, I have 4 variables (DESCA, DESCB, DESCC & DESCD), they may be nil, or may have a value.  If they have a value I need to concatenate these with a "_" in-between.  Without a bunch of "if" statements, what's the best way to do this?

 

Thanks,

0 Likes
Accepted solutions (1)
3,489 Views
4 Replies
Replies (4)
Message 2 of 5

MunteanStefan
Contributor
Contributor
Accepted solution
(setq l (vl-remove nil (list DESCA DESCB DESCC DESCD))
      str (car l)
)
(foreach x (cdr l) (setq str (strcat str "_" x)))
Message 3 of 5

Kent1Cooper
Consultant
Consultant

[Never mind -- Message 2 is much better than my thoughts.]

Kent Cooper, AIA
0 Likes
Message 4 of 5

john.uhden
Mentor
Mentor

Actually, we should check if any of the variables is not a string, not just nil...

(defun string-p (var)(= (type var) 'STR))
(setq l (vl-remove-if-not 'string-p (list DESCA DESCB DESCC DESCD))
      str (car l)
)

 OR, we could force all the variables to be strings

(setq l (mapcar 'vl-princ-to-string (list desca descb descc descd)))

John F. Uhden

0 Likes
Message 5 of 5

hak_vz
Advisor
Advisor

@gcsjlewisI will rephrase your request, and make it more generic solution. Here is a function that concatenates elements of the list of arbitrary length with some concatenation symbol (string), and removes all elements of the list that equal nil. If all elements of the list are nil it will return string " " to suppress potential error if function is joined with other string dealing function.

 

 

Usage: (cancan (list DESCA DESCB DESCC DESCD)  "-")

 

(defun cancan (lst csym / i j str lst mklist)
(defun mklist (obj)(if (listp obj)obj(list obj)))
	(cond
		((= (type csym) 'STR)
			(setq 
				i -1
				str "" 
				lst (vl-remove nil (mklist lst))
			)
			(cond ((and lst)
			(setq lst (mapcar 'vl-princ-to-string lst) j (- (length lst)1))
			(while (< (setq i (1+ i)) j)(setq str (strcat str (nth i lst)  csym)))
			(strcat str (last lst)))
			(T " ")
			)
		)
		(T (princ "\nConcatenation symbol is not a string!")(princ))
	)
)

 

 

Miljenko Hatlak

EESignature

Did you find this post helpful? Feel free to Like this post.
Did your question get successfully answered? Then click on the ACCEPT SOLUTION button.
0 Likes