/*
* Copyright 2008-2010 the original author or authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
//package org.kaleidofoundry.core.util;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.Reader;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.StringTokenizer;
/**
* String Helper static method
*
* @author Jerome RADUGET
*/
public abstract class StringHelper {
/**
* Find and replace all occurrences of the string
*
*
* Assertions :
* assertNull(StringHelper.replaceAll(null, null, null));
* assertNull(StringHelper.replaceAll(null, "a", "b"));
* assertEquals("anullc", StringHelper.replaceAll("abc", "b", null));
* assertEquals("", StringHelper.replaceAll("", "", ""));
* assertEquals("foo", StringHelper.replaceAll("a", "a", "foo"));
* assertEquals(".foo", StringHelper.replaceAll(".a", "a", "foo"));
* assertEquals("foo.", StringHelper.replaceAll("a.", "a", "foo"));
* assertEquals("..foo...foo..foo", StringHelper.replaceAll("..a...a..a", "a", "foo"));
* assertEquals("foo...foo..foo.", StringHelper.replaceAll("ab...ab..ab.", "ab", "foo"));
*
*
* @param source source string
* @param findToken string to search for
* @param replaceToken string to replace found tokens with
* @return the modified string
*/
public static String replaceAll(String source, final String findToken, final String replaceToken) {
if (source == null) { return null; }
StringBuilder sb = null;
int pos;
do {
if ((pos = source.indexOf(findToken)) < 0) {
break;
}
if (sb == null) {
sb = new StringBuilder();
}
if (pos > 0) {
sb.append(source.substring(0, pos));
}
sb.append(replaceToken);
source = source.substring(pos + findToken.length());
} while (source.length() > 0);
if (sb == null) {
return source;
} else {
sb.append(source);
return sb.toString();
}
}
}