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!
4 Answers
Yeah, a for loop could work, but just be careful with edge cases, like if there aren’t three spaces!
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!
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.
Awesome, that worked for me! Thanks a lot!
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)!
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.

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