Strings - foo[0,0] vs.. foo[-1,0] ?

M

Marc Heiler

Since some time I have used this to prepend something to a string:

string = 'bc'
string[0,0] = 'a'

Resulting in:

'abc'

Then I recently wanted to append something to a string.
Of course there exists the << method already

string = 'ab'
string << 'c'

But there does not seem to be a way via []
Using

string[-1,0] = 'c'

will add at the position before. Is it true that with the
[] method on string one can not append just one character to it?
 
M

Matthew K. Williams

Since some time I have used this to prepend something to a string:

string = 'bc'
string[0,0] = 'a'

Resulting in:

'abc'

Then I recently wanted to append something to a string.
Of course there exists the << method already

string = 'ab'
string << 'c'

But there does not seem to be a way via []
Using

string[-1,0] = 'c'

will add at the position before. Is it true that with the
[] method on string one can not append just one character to it?


string[string.size,0]='c' works

But I think string << 'c' is clearer

YMMV
 
M

Marc Heiler

Matthew said:
Of course there exists the << method already
[] method on string one can not append just one character to it?
string[string.size,0]='c' works

But I think string << 'c' is clearer

YMMV

Thanks.

I agree with you, string << 'c' is a lot clearer.

Can someone explain the code to me? I am that thickhead. :D

This code works:

string = 'ab'
string[2, 0] = 'c'

But why does that work?

And via -1, 0 it would not work right?

I think I am confused why -1, 0 does not work. (My poor brain gives up
too easily...)
 
S

Sascha Abel

string[i,1] gives you the char at index i,

string[i,0] gives you not the char but some kind of a marker just
*before* that char.

So string[i,1]= 'X' overwrites that char, while

string[i,0] = 'X' inserts before it.

string[-1,1] gives you the last char of string, accordingly

string[-1,0] gives you that marker just *before* the last char.

You would have to do something like string[-0,0] to get *behind* the
last char if you want to count from the end of the string, which is not
possible so you have to count from the beginning: string[string.size,0]
 
M

Marc Heiler

I think that finally helped, thanks.

It is a lot easier for my brain if I use the word *marker* as well. :)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,156
Messages
2,570,878
Members
47,413
Latest member
KeiraLight

Latest Threads

Top