Wednesday, 11 December 2013

Replacing multiple spaces with single space

I am considering the highest voted regular expression and string questions at Stackoverflow to show parse usage in rebol2. It goes without saying that these questions are for other languages than rebol.

First question: Replacing multiple spaces with single space.

How to do this?

  1. Split the string with respect to spaces, and get the result in a block.
  2. Append the strings in the block one by one, with a single space in between.

1. Splitting a string

Splitting a string using parse is simple. Just provide 'none' as the parse parameter. It automatically gives the result in a block

Code:
parse "Provide none to split a string by spaces" none
;; == ["Provide" "none" "to" "split" "a" "string" "by" "spaces"]
view raw none hosted with ❤ by GitHub

2. Appending strings in block with spaces

Rebol has forall and append for us. In this example, we use "-" as a divider between words.

Code:
split-block: ["This" "-" "is" "-" "Sparta" "!"]
result-string: "" ;; empty string
forall split-block [
append result-string (first split-block)
]
;; == "This-is-Sparta!"
view raw appendAndForall hosted with ❤ by GitHub


Function:

Now we connect the two parts. 

Code:
replace-multiple-spaces: func [str [string!]] [
no-space-block: parse str none
return-string: copy ""
append return-string (first no-space-block)
no-space-block: (next no-space-block)
forall no-space-block [
append return-string " "
append return-string (first no-space-block)
]
return return-string
]

Line 2 divides the string by spaces and puts it in a block (no-space-block). Line 3 initializes an empty string. Line 5 make sure that return-string is initialized with the first word. Line 6 ensures that the first word is not processed in the loop later.

Usage:
>> replace-multiple-spaces "Once upon a time ....."
== "Once upon a time ....."
>> replace-multiple-spaces "1 2 3 4 5 6 7 8"
== "1 2 3 4 5 6 7 8"
>> replace-multiple-spaces "Brazil 0 - 5 India" ;; Someday in football
== "Brazil 0 - 5 India"
view raw usage hosted with ❤ by GitHub


Feel free to ask anything in comments.


No comments:

Post a Comment