Home   Archive   Permalink



replace last character

How do I replace the last character of a string ?
    
e.g if I have c: 'abcdef'
and I want to change the last character to 'z'
so that c becomes 'abcdez'
    
I was trying change/part c 'z' length? c
it did not work.

posted by:   change last text     8-Dec-2016/22:23:06-8:00



str/(length? str): "z"
    
That's clunky, but works.

posted by:   Sunanda     9-Dec-2016/1:52:35-8:00



Another way would be:
    
change back tail c "z"

posted by:   Chris     9-Dec-2016/2:25:18-8:00



Another way:
    
poke c length? c #"z"

posted by:   Nick     9-Dec-2016/6:34:20-8:00



BTW, your original way also works, if you use double quotes:
    
change/part c "z" length? c

posted by:   Nick     9-Dec-2016/6:40:21-8:00



@nick, when I use double quote it changes the whole string into z , rather than abcdez. pls see below
    
c: "abcdef"
== "abcdef"
>> change/part c "z" length? c
== ""
>> c
== "z"

posted by:   change last text     9-Dec-2016/23:20:32-8:00



@sunanda, getting an error when trying str/(length? str): "z"
    
>> c: "abcdef"
== "abcdef"
>> c/(length? c): "z"
** Script Error: Invalid argument: z
** Where: halt-view
** Near: c/(length? c): "z"
>>

posted by:   change last text     9-Dec-2016/23:24:03-8:00



@nick - poke c length? c #"z" works.
    
>> c: "abcdef"
== "abcdef"
>> poke c length? c #"z"
== #"z"
>> c
== "abcdez"
>>
    
    
To all of you, thanks a lot for helping out.

posted by:   change last text     9-Dec-2016/23:27-8:00



Sunanda's example works if you change the "z" string to a #"z" character:
    
c/(length? c): #"z"

posted by:   Nick     10-Dec-2016/7:44:45-8:00



thanks Nick.
for my own learning process, what does the # mean?
    
I did a search on the site to see what # mean, the only place I could find something is in rebolcore-16.html.    
    
is it converting to binary in c/(length? c): #"z"
and poke c length? c #"z"

posted by:   change last text     10-Dec-2016/8:28:42-8:00



I also saw # being used as char in chapter 4 - http://www.rebol.com/docs/core23/rebolcore-4.html#section-3

posted by:   change last text     10-Dec-2016/9:22-8:00



The # symbol is used to refer to the char! datatype (a single character). The string and character datatypes are different, so if a function expects a char!, and gets a string!, you'll get an error.
    
BTW, you can cast a char! from a single character string using:
    
to-char "z"
== #"z"

posted by:   Nick     10-Dec-2016/9:53:52-8:00