From e00c6cc0661767b8d044409865620fb0e4be7fc9 Mon Sep 17 00:00:00 2001 From: mdb Date: Tue, 13 Feb 2001 19:54:43 +0000 Subject: [PATCH] Added a method for replacing text within a string. git-svn-id: https://samskivert.googlecode.com/svn/trunk@44 6335cc39-0255-0410-8fd6-9bcaacd3b74c --- .../java/com/samskivert/util/StringUtil.java | 28 ++++++++++++++++++- 1 file changed, 27 insertions(+), 1 deletion(-) diff --git a/projects/samskivert/src/java/com/samskivert/util/StringUtil.java b/projects/samskivert/src/java/com/samskivert/util/StringUtil.java index 7f6b11bd..94ed7f0d 100644 --- a/projects/samskivert/src/java/com/samskivert/util/StringUtil.java +++ b/projects/samskivert/src/java/com/samskivert/util/StringUtil.java @@ -1,5 +1,5 @@ // -// $Id: StringUtil.java,v 1.2 2000/10/31 00:51:13 mdb Exp $ +// $Id: StringUtil.java,v 1.3 2001/02/13 19:54:43 mdb Exp $ package com.samskivert.util; @@ -16,6 +16,32 @@ public class StringUtil return (value == null || value.trim().length() == 0); } + /** + * Returns a new string based on source with all + * instances of before replaced with after. + */ + public static String replace (String source, String before, String after) + { + int pos = source.indexOf(before); + if (pos == -1) { + return source; + } + + StringBuffer sb = new StringBuffer(source.length() + 32); + + int blength = before.length(); + int start = 0; + while (pos != -1) { + sb.append(source.substring(start, pos)); + sb.append(after); + start = pos + blength; + pos = source.indexOf(before, start); + } + sb.append(source.substring(start)); + + return sb.toString(); + } + /** * Converts the supplied object to a string. Normally this is * accomplished via the object's built in toString()