How to insert a character into a string a specific location?

How to insert a character into a string a specific location?

mid-awe
Collaborator Collaborator
2,142 Views
6 Replies
Message 1 of 7

How to insert a character into a string a specific location?

mid-awe
Collaborator
Collaborator

Hi all,

 

I am sure this is an easy task but I am having some trouble remembering how to insert a Letter into a string at a specific location. 

 

I'm trying to get the (VL-FILENAME-BASE (GETVAR 'DWGNAME)) and insert a (chr 86) after the 8th character, so that the inserted letter becomes the 9th letter/number only if it is not already present.

 

example:

23-01472r7

becomes:

23-01472Vr7

 

I hope that this makes sense. Any help is greatly appreciated.

 

Thank you in advance.

0 Likes
Accepted solutions (2)
2,143 Views
6 Replies
Replies (6)
Message 2 of 7

Kent1Cooper
Consultant
Consultant
Accepted solution

@mid-awe wrote:

.... 

I'm trying to .... insert a (chr 86) after the 8th character, so that the inserted letter becomes the 9th letter/number only if it is not already present.

....


How about something like:

 

(if (/= (substr YourString 9 1) "V"); not already present

  (setq YourString (strcat (substr YourString 1 8) "V" (substr YourString 9)))

)

 

If the original is not at least 9 characters long, it will simply add "V" to the end.

Kent Cooper, AIA
Message 3 of 7

mid-awe
Collaborator
Collaborator
Thank you Kent, that did it perfectly.
0 Likes
Message 4 of 7

Moshe-A
Mentor
Mentor
Accepted solution

hi,

 

check this:

 

(defun insert_string (string str p)
 (if (not (vl-string-search string str))
  (if (and (not (minusp p)) (<= p (strlen string)))
   (if (= p 0)
    (strcat str string)
    (strcat (substr string 1 p) str (substr string (1+ p)))
   )
  )
 ) 
)

 

(insert_string "23-01472r7" "V" 8)
"23-01472Vr7"

 

 

Moshe

Message 5 of 7

mid-awe
Collaborator
Collaborator
Thank you Mosh for this reusable solution.
0 Likes
Message 6 of 7

Moshe-A
Mentor
Mentor

thank you very much mid-awe

 

i forgot to insert p argument in (vl-string-search) this ensures that only if str

does not exist in the position in question the new add string is inserted.

 

 

(defun insert_string (string str p)
  (if (not (vl-string-search string str p))
   (if (and (not (minusp p)) (<= p (strlen string)))
    (if (= p 0)
     (strcat str string)
     (strcat (substr string 1 p) str (substr string (1+ p)))
    )
   )
  )  
)

 

notice that the (insert_string) function let you insert a str in front of string (p=0)

and at the end but it won't let you insert a string if the index p is out of range

 

 

moshe

 

 

 

Message 7 of 7

mid-awe
Collaborator
Collaborator
Thanks again 🙂
0 Likes