• Post Reply Bookmark Topic Watch Topic
  • New Topic

Strings and char replacement  RSS feed

 
James Barber
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
need direction! character replacement in string.
If I have a String "aaaaa" and what to replace just one "a",
with a different character say "J" how can I do this?
Everything I've tried replaces all not just one
 
Paweł Baczyński
Bartender
Posts: 2083
44
Firefox Browser IntelliJ IDE Java Linux Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Which one of "a" do you want to replace? The first? So get an index of first occurence using String#indexOf and than perform manual replace using String#substring and concatenation (+ operator).
 
Matthew Brown
Bartender
Posts: 4568
9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There's also a replaceFirst() method in the String class (that takes a regular expression).

If it's not the first then you need to decide how you want to identify the specific character you want to replace - how to best do it could vary.
 
Campbell Ritchie
Marshal
Posts: 56536
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I would suggest you put the String into a StringBuilder‍←link, and use its methods. StringBuilder is specifically designed for that sort of manipulation, so it does it well.
 
James Barber
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
this is what I came up with thanks for the help

 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!