[Haskell-beginners] How to remove leading and trailing non-alpha characters, and multiple consecutive spaces?

Costello, Roger L. costello at mitre.org
Fri Jun 7 00:36:27 CEST 2013


Hi Folks,

I have a string that contains a person's name. 

Prior to the person's name there may be some non-alpha characters. 

After the person's name there may be some non-alpha characters.

Between the person's first name and last name there should be only one space.

I want to remove the leading and trailing non-alpha characters and remove the extra spaces.

Here is an example string:

s = "     \"    John     Doe    \"    "

After processing, I should have:

	John Doe

Below is my implementation. Is there is a shorter and more efficient implementation? 

----------------------------------
import Data.Char
import Data.List

s = "     \"    John     Doe    \"    "

-- remove leading non-alpha characters

t1 = dropWhile (not . isAlpha) s		-- returns "John     Doe    \"    "

-- break the string up into a list of words, 
-- delimited by white space

t2 = words t1				-- returns ["John","Doe","\""]

-- create a string consisting of the first 
-- name, space, last name

t3 = t2!!0 ++ " " ++ t2!!1 		-- returns "John Doe"

-- Put it all together:

t4 = ((words . dropWhile (not . isAlpha)) s)!!0 ++ " " ++ ((words . dropWhile (not . isAlpha)) s)!!1





More information about the Beginners mailing list