From: Sven E. <sve...@we...> - 2005-02-27 13:32:41
|
I was looking for a routine which replaces 1, more or all occurrences of a certain string `a_old' in another string `a_text' with a string `a_new'. Since I did not find one (I hope I did not oversee it) I came up with the following routine: ____________________________________________________________________________= _______________________________________ replaced_string (a_text, a_old, a_new: STRING; a_max_count: INTEGER):= STRING is -- `a_text' with each of the first `a_max_count' occurences of `a_old'= have been replaced with -- `a_new'. If `a_max_count' is -1 all occurences are replaced. require a_text_not_void: a_text /=3D Void a_new_not_void: a_new /=3D Void a_old_not_void: a_old /=3D Void local idx: INTEGER a_count: INTEGER a_old_count: INTEGER a_start: INTEGER a_end: INTEGER do create Result.make (a_text.count) a_old_count :=3D a_old.count a_count :=3D a_max_count a_start :=3D 1 a_end :=3D a_text.substring_index (a_old, a_start) from until a_end =3D 0 or else a_count =3D 0 loop Result.append_string (a_text.substring (a_start, a_end - 1)) Result.append_string (a_new) a_start :=3D a_end + a_old_count a_end :=3D a_text.substring_index (a_old, a_start) a_count :=3D a_count - 1 end Result.append_string (a_text.substring (a_start, a_text.count)) ensure replaced_string_not_void: Result /=3D Void end ____________________________________________________________________________= _______________________________________ Would it make sense to add this to KL_STRING_ROUTINES? - Sven |