From: Eric B. <er...@go...> - 2005-02-27 16:04:05
|
Sven Ehrke wrote: > 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 /= Void > a_new_not_void: a_new /= Void > a_old_not_void: a_old /= 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 := a_old.count > a_count := a_max_count > > a_start := 1 > a_end := a_text.substring_index (a_old, a_start) > from until a_end = 0 or else a_count = 0 loop > Result.append_string (a_text.substring (a_start, a_end - 1)) > Result.append_string (a_new) > a_start := a_end + a_old_count > > a_end := a_text.substring_index (a_old, a_start) > a_count := a_count - 1 > end > Result.append_string (a_text.substring (a_start, a_text.count)) > ensure > replaced_string_not_void: Result /= Void > end > ___________________________________________________________________________________________________________________ > > Would it make sense to add this to KL_STRING_ROUTINES? This routine does not seem to be unicode string friendly. Also, I wonder whether it should be in KL_STRING_ROUTINES or in a class in library/string (because it's like splitting the string in chunks, replacing some chunks and concatenating back the resulting chunks. -- Eric Bezault mailto:er...@go... http://www.gobosoft.com |