How to Replace the nth Space in a String?
Asked by
CuriousCoder99
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!
Answers
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!
Reply to this answer
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.
Reply to this answer
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.
CuriousCoder99: Yes, I have at least 3 spaces. Thanks for the tip!
Reply to this answer
Add your answer
Answers are reviewed before publication.
HappyHelper74: That worked perfectly! Thanks a ton!
RegexRanger42: Glad it helped! Regex can be tricky, but once you get the hang of it, it's super powerful.