TheSwamp

Code Red => AutoLISP (Vanilla / Visual) => Topic started by: like_citrus on March 15, 2020, 07:11:09 AM

Title: String manipulation - block name
Post by: like_citrus on March 15, 2020, 07:11:09 AM
Is it possible to truncate a string up to a certain character?
With the code below, a block in inserted which joins the file name "UniversalBeams_610UB125" and the date "20200315.185925", to give the block name "UniversalBeams_610UB125-20200315.185925"
Is if possible to truncate up to and including the underscore character "_".
The final name would be "610UB125-20200315.185925".


Code: [Select]
(defun blkins (blkname) ; the name of the program or function must be defined in the first statement
  (command "_.-insert" (strcat blkname "-" (rtos (getvar "cdate") 2 6) "=" blkname) pause 1 "" 0)
)
; "strcat": Returns a string that is the concatenation of multiple strings
; "rtos" Converts a number into a string
; "1" is the scale, "0" is the rotation
Title: Re: String manipulation - block name
Post by: MP on March 15, 2020, 11:15:31 AM
look up: vl-string-position and substr
Title: Re: String manipulation - block name
Post by: like_citrus on March 15, 2020, 11:54:24 PM
Thanks for the suggestion.
I've tried below but get an error message. More than likely my syntax is not right.
If I replace "vl-string-position "_" blkname 1" with "16" ... it's all good ... however this will not suit all items, as the prefix length is variable.

Code: [Select]
(defun blkins (blkname)
 (command "_.-insert" (substr (strcat blkname "-" (rtos (getvar "cdate") 2 6) "=" blkname) vl-string-position "_" blkname 1) pause 1 "" 0)
)
Title: Re: String manipulation - block name
Post by: BIGAL on March 16, 2020, 02:05:49 AM
You need to read the help looks for a key number

(vl-string-position (ascii "_") blkname 1)
Title: Re: String manipulation - block name
Post by: like_citrus on March 16, 2020, 02:45:15 AM
Thanks for the input BIGAL.
It's getting closer.

The final name comes out as "s_610UB125-20200315.185925".
For some reason the characters "s_" still remain.

Code: [Select]
(defun blkins (blkname)
(command "_.-insert" (substr (strcat blkname "-" (rtos (getvar "cdate") 2 6) "=" blkname) (vl-string-position (ascii "_") blkname 1)) pause 1 "" 0)
)
Title: Re: String manipulation - block name
Post by: Dlanor on March 16, 2020, 05:41:25 AM
vl-string-position has a base 0 substr has a base 1. vl-string-postion will give you the position of the character where 0 is the first character. To eliminate it from the string add 1, but substr uses 1 as the first character, so you need to add 2 to achieve the same result. 

so

Code - Auto/Visual Lisp: [Select]
  1. (+ (vl-string-position (ascii "_") blkname 1) 2)
Title: Re: String manipulation - block name
Post by: like_citrus on March 16, 2020, 09:55:05 AM
Thank you very much dlanor.
A great outcome for my purpose.
Cheers to all for their input.