Remove spaces before and after punctuation

can you test time my version?

set theString to "this , is - a ? test / this ! is ( a ) test [ this ] is { a } test : this ; is two  spaces and three   spaces" & linefeed

repeat 10 times
	set theString to theString & theString
end repeat

repeat with tids in {{" ", "  "}, {"/", "/ "}, {"-", "- "}, {"(", "( "}, {"[", "[ "}, {"{", "{ "}, {",", " ,"}, {"-", " -"}, {"?", " ?"}, {"/", " /"}, {"!", " !"}, {")", " )"}, {"]", " ]"}, {"}", " }"}, {":", " :"}, {";", " ;"}}
	set tids to contents of tids
	set fnd to item 2 of tids
	set reps to item 1 of tids
	repeat while (offset of fnd in theString) > 0
		set text item delimiters to fnd
		set tmp to text items of theString
		set text item delimiters to reps
		set theString to tmp as text
	end repeat
end repeat
set the clipboard to theString

Robert. To compare like with like, I modified your script to get the source text from the clipboard. The timing was 72 milliseconds. As written, your script took 67 milliseconds.

can you test this slightly modified version. it seems to be faster for me,

set THESTRING to the clipboard

repeat with tids in {{" ", "  "}, {"/", "/ "}, {"-", "- "}, {"(", "( "}, {"[", "[ "}, {"{", "{ "}, {",", " ,"}, {"-", " -"}, {"?", " ?"}, {"/", " /"}, {"!", " !"}, {")", " )"}, {"]", " ]"}, {"}", " }"}, {":", " :"}, {";", " ;"}}
	set tids to contents of tids
	set fnd to item 2 of tids
	set reps to item 1 of tids
	repeat while fnd is in THESTRING
		set text item delimiters to fnd
		set tmp to text items of THESTRING
		set text item delimiters to reps
		set THESTRING to tmp as text
	end repeat
end repeat
1 Like

Robert. Your revised script took 65 milliseconds. Just for the sake of consistency, I added a line that set the clipboard to THESTRING before running the tests.

FWIW, the timing result was 52 milliseconds if I deleted the repeat loop that tests to see if fnd is in THESTRING and added a sublist that replaces three spaces with one. This changes the result if there are 5 or more consecutive spaces, but that would not seem a significant issue.