• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Tim Cooke
  • Campbell Ritchie
  • Ron McLeod
  • Junilu Lacar
  • Liutauras Vilda
Sheriffs:
  • Paul Clapham
  • Jeanne Boyarsky
  • Henry Wong
Saloon Keepers:
  • Tim Moores
  • Tim Holloway
  • Stephan van Hulst
  • Piet Souris
  • Carey Brown
Bartenders:
  • Jesse Duncan
  • Frits Walraven
  • Mikalai Zaikin

Substring function appears not to work in lists

 
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Can someone explain why this won't work?

output: ['bananas', 'apples', 'pears']

The list remains unchanged, even though it is a mutable type. It works fine it it's not in a list:

output: ['balloons', 'apples', 'pears']

Thanks
Jason
 
Saloon Keeper
Posts: 4992
186
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Strings are immutable.

Your array contains pointers to the strings. In your for-loop, fruit is just another pointer to the corresponding string (it is a copy of the original pointer, this is called 'passing by value'). So, although you change that fruit-pointer, the original pointer in your array (pointing to "bananas") remains unchanged. Can you now explain why text does get changed?
 
Jason de Vere
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Sorry, what I meant was that the list is mutable, since that is what I was changing. The string was meant to be totally replaced with the line: fruit = fruit.replace(substring, "alloon")

I didn't really understand your explanation but it did help me see that I never actually touched the list. I would have said I changed a copy of one of the list's values, but I'm sure that's not correct either. My solution would be:



Thanks for the help.
reply
    Bookmark Topic Watch Topic
  • New Topic