Reputation: 39
I am looking for the easiest way to take a string, "ACB1 C123" and swap the positions of the space and the following character to "ACB1C 123".
Upvotes: 0
Views: 235
Reputation: 72312
This code does the swap with captures:
s= "ACB1 C123"
print(s:gsub(" (.)","%1 "))
However, it does it for all occurrences of a space followed by a character.
To limit the swap to the first occurrence, use
print(s:gsub(" (.)","%1 ",1))
Upvotes: 0
Reputation: 553
Someone else will probably cook up some cool regex gsub but until then you can use these very simple and ugly string modifications and continue what you're doing:
string = "ACB1 C123"
space = string:find(" ")
part = string:sub(space, space+1):gsub("(.)(.)", "%2%1")
newstring = string:sub(0, space-1) .. part .. string:sub(space+2)
print(newstring)
And if you don't like multiple lines here is an even uglier one liner ;)
string:sub(0, string:find(" ")-1) .. string:sub(string:find(" "), string:find(" ")+1):gsub("(.)(.)","%2%1") .. string:sub(string:find(" ")+2)
Upvotes: 1