Page 1 of 1

Function Trim to remove spaces

Posted: Tue Mar 24, 2015 9:28 am
by manumart1
I miss a function Trim to remove leading and trailing spaces inside an array of chars. I haven't found it.
I think it is a general utility function to process the input from the user, and worth to be somewhere, perhaps is module String, instead of everybody having to write his own version.
Here is my version:

Code: Select all

PROCEDURE Trim* (VAR s: ARRAY OF CHAR);
(* Leading and trailing spaces are removed *)
	VAR indexLastChar, beg, end, i, j: INTEGER;
BEGIN
	indexLastChar := LEN(s$) - 1;
	beg := 0; WHILE s[beg] = " " DO INC(beg) END;
	IF s[beg] = 0X THEN (* s is all spaces *)
		s[0] := 0X
	ELSE
		end := indexLastChar; WHILE s[end] = " " DO DEC(end) END;
		IF beg > 0 THEN
			i := 0; j := beg;
			WHILE j <= end DO s[i] := s[j]; INC(i); INC(j) END;
			s[i] := 0X
		ELSIF end < indexLastChar THEN
			s[end + 1] := 0X
		END
	END
END Trim;
Regards

Re: Function Trim to remove spaces

Posted: Tue Mar 24, 2015 11:16 am
by cfbsoftware
The string handling utilities from POW! Oberon's Opal library have been ported to Component Pascal. You can download them from:

http://www.zinnamturm.eu/downloadsOS.htm#Opal

However, my favourite implementation is the versatile approach used in ETHOberon's Utilities module:

Code: Select all

(** removes all occurrences of 'c' at the head of 'string' *)
PROCEDURE TrimLeft*(VAR string: ARRAY OF CHAR; c: CHAR);

Code: Select all

(** removes all occurrences of 'c' at the end of 'string' *)
PROCEDURE TrimRight*(VAR string: ARRAY OF CHAR; c: CHAR);

Code: Select all

(** removes all occurrences of 'c' at both ends of 'string' *)
PROCEDURE Trim*(VAR string: ARRAY OF CHAR; c: CHAR);
BEGIN
	TrimLeft(string, c);
	TrimRight(string, c)
END Trim;
The full source code of these and other useful string-handling functions is included with the ETH Oberon distribution.

Re: Function Trim to remove spaces

Posted: Wed Mar 25, 2015 11:53 am
by manumart1
Thank you, Chris.
I did not know about the subsystem Opal of BlackBox nor the POW! development environment.

Re: Function Trim to remove spaces

Posted: Wed Mar 25, 2015 9:24 pm
by Ivan Denisov
In my BlackBox assembly there is function Trim in Strings.

There is the diff of my Strings and Strings from BB1.6rc6
http://redmine.molpit.com/projects/blac ... fcf743464d

Also in this diff you can see your Find bugfix :)