I'm looking for a way to replace the nth occurrence of a character in a string, specifically the 3rd space, with a dash. For example, if I start with "The quick brown fox jumped over the lazy dog", I'd like it to turn into "The quick brown-fox jumped over the lazy dog". I'm working with file names, so the content can vary, and I'm trying to avoid using split operations or counting character positions. Any help would be appreciated!
3 Answers
Regex is definitely the way to go! Just make sure that in your string, you actually have at least 3 spaces; otherwise, it won't replace anything.
If you're not into regex, you could also loop through the string and count the spaces. When you hit the 3rd space, just swap it with a '-' and then break out of the loop.
You can accomplish this using a regex pattern. Try this PowerShell command: `$string -replace '(?<=^[^ ]*( [^ ]*){2}) ','-'`. Just replace "2" with the number of spaces you want to ignore beforehand. This will effectively replace the 3rd space with a dash!
That worked perfectly! Thanks a ton!
Glad it helped! Regex can be tricky, but once you get the hang of it, it's super powerful.

Yes, I have at least 3 spaces. Thanks for the tip!