How do I replace the nth occurrence of a character in a string?

January 19, 2026 4 answers
Asked by CleverTurtle93
I'm trying to find a way to replace the third space in a string with a dash. For example, I'd like "The quick brown fox jumped over the lazy dog" to turn into "The quick brown-fox jumped over the lazy dog". I'm working with filenames where the words change frequently, so I'm trying to avoid using methods like splitting the string by spaces or counting to the 15th character. Any suggestions would be appreciated!

Answers

LoopMaster99
If you're not into regex, another option is to loop through the string and count the spaces. When you hit the third space, just replace it with a '-'. That way you can control the process better.
Reply to this answer
CodeNinja42
You can use a regex pattern for this! For example, with PowerShell, you can do something like `$string -replace '(?<=^[^ ]*( [^ ]*){2}) ','-'`. Just change "2" to the position you want to replace. This approach is pretty flexible if you know how many spaces you're targeting.

HelpfulHannah56: Awesome, that worked for me! Thanks a lot!

RegexFan88: I love regex too! It's a bit intimidating at first, but once you get the hang of it, it's pretty powerful. If you want to dive deeper, check out [this regex tutorial](https://regex101.com/r/WTfi6n/1)!

Reply to this answer
ScriptWizard75
Using regex is definitely the way to go. Just make sure you know how many spaces you have in your string. If you can confirm there are always three or more, you should be set!

CleverTurtle93: Yes, there are usually three spaces, so that should work!

Reply to this answer
SubtleCoder21
Yeah, a for loop could work, but just be careful with edge cases, like if there arenโ€™t three spaces!
Reply to this answer

Add your answer

Answers are reviewed before publication.

Related Discussions