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:

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:

Function:

Now we connect the two parts. 

Code:

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:

Feel free to ask anything in comments.


No comments:

Post a Comment