Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

How do you add a space after every character in a string?

Asked by 8 years ago

I've checked the string manipulation page on to Wiki, but couldn't find what I was looking for. http://wiki.roblox.com/index.php?title=Function_dump/String_manipulation

Does any know if it's possible or how to add a space after ever character in a string?

** EDIT: Never mind I just removed all the spaces instead :) **

2 answers

Log in to vote
2
Answered by 8 years ago

I don't really agree with Goulstem's solution. Forgive me for wanting better solutions.

local str = "This should have a space after every character"
local newstr = str:gsub('(.)','%1 ');

A character in this case is literally anything, meaning it will actually also insert spaces after spaces.


How does it work?

  • (.) captures any character
  • %1 stands for the character we captured
  • puts a space after it.
Ad
Log in to vote
1
Answered by
Goulstem 8144 Badge of Merit Moderation Voter Administrator Community Moderator
8 years ago

To add a space after every character in a string, iterate through the string using gmatch. Use the string pattern %w to indicate an iteration on any found alphanumeric character. You can see a list of string patterns here.

While iterating, start creating a new string that consists of everything the old one had, but add a space in between.

local str = "Hello my name is Goulstem" --Your String
local newstr = "" --The new string

for i in str:gmatch("%w") do
    newstr = i.." " --Add a space
end
print(newstr);
0
String concatenation like that is really really slow. User#6546 35 — 8y

Answer this question