Replacing characters at certain positions in strings
Hi guys, first time on the forum here and I have just spent about 10 minutes searching through these forums looking for an answer to my question, but I can't find one.
It's quite basic, but here is my problem. I need to simulate a race (I've seen similar threads on this but not with my question), and the racetrack is basically a string of ------ (65 chars long).
There are two animals racing, a hare and a tortoise. I have programmed most of it but I'm unsure on how to proceed with displaying the positions of each animal on the racetrack. For example, if the tortoise is at position 50, there should be a "T" at the 50th position on the racetrack. If it then moves up by 5 spots, the "T" should appear at position 55, and a "-" should reappear at position 50.
At first I thought about swapping two tiles, but I don't think that's possible without the use of arrays (which I'm not allowed using).
So I'm thinking that I should basically just reset the track to all "----" after each position move and then simply add the "H" or "T" to the new position. Only problem is that I'm not sure how to do that.
In basic English, I'd like to: "Replace character at position "50" (or wtv else position) with an "H" or a "T"."
Any help would be greatly appreciated!
Re: Replacing characters at certain positions in strings
Since Strings are immutable, you will have to build a new String from the current String. Can you use the StringBuilder or StringBuffer classes? Otherwise use the methods of the String class to get the unchanged parts of the String and use them to build the new String.
Re: Replacing characters at certain positions in strings
Thanks for your reply! I had actually gone in and dug into a java book I had and was able to find the StringBuilder and StringBuffer classes, and used the "getCharAt" method. To be honest, I'm not sure if I'm allowed to use them since we didn't actually learn about them, but at this point my program is almost done so it'll have to do.