help-gnu-emacs
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: left-trim and right-trim for strings


From: Klaus Berndl
Subject: Re: left-trim and right-trim for strings
Date: 23 Sep 2002 12:19:52 +0200
User-agent: Gnus/5.09 (Gnus v5.9.0) Emacs/21.1

On Mon, 23 Sep 2002, Oliver Scholz wrote:



>  Klaus Berndl <address@hidden> writes:
>  
> > left-trim: Removing any leading whitespace from a string.
> > right-trim: Removing any trailing whitespace from a string.
> >
> > Are there such functions available in elisp or have i to write them
> > for myself?
>  
>  Probably rather a dirty trick, but you could abuse `split-string':
>  
>  (car (split-string "    Dies ist ein Test." "^[\n\t ]*"))
>  (car (split-string "Dies ist ein Test.    " "[\n\t ]*$"))
>  
>      -- Oliver


Here is a set of string trimming functions:

,----
| (defun str-excessive-trim (str)
|   "Return a string where all double-and-more whitespaces in STR are replaced
| with a single space-character."
|   (let ((s str))
|     (while (string-match "[ \t][ \t]+" s)
|       (setq s (concat (substring s 0 (match-beginning 0))
|                       " "
|                       (substring s (match-end 0)))))
|     s))
| 
| (defun str-left-trim (str)
|   "Return a string stripped of all leading whitespaces of STR."
|   (or (car (split-string str "^[\n\t ]*")) ""))
|     
| (defun str-right-trim (str)
|   "Return a string stripped of all trailing whitespaces of STR."
|   (or (car (split-string str "[\n\t ]*$")) ""))
| 
| (defun str-trim (str)
|   "Applies `str-right-trim' and `str-left-trim' to STR."
|   (str-left-trim (str-right-trim str)))
| 
| (defun str-full-trim (str)
|   "Applies `str-trim' and `str-middle-trim' to STR."
|   (str-excessive-trim (str-trim str)))
`----

Thanks to Oliver and Jesper!

Any further suggestions?

Ciao,
Klaus

-- 
Klaus Berndl                    mailto: address@hidden
sd&m AG                         http://www.sdm.de
software design & management
Thomas-Dehler-Str. 27, 81737 M√ľnchen, Germany
Tel +49 89 63812-392, Fax -220


reply via email to

[Prev in Thread] Current Thread [Next in Thread]