Here you can find the source of replaceStr(StringBuilder original, char replacementChar, Stream
Parameter | Description |
---|---|
original | the string to perform a replacement on |
replacementChar | the character used to replace each character of a matching string |
stringsToReplace | strings that may appear in the original string which are subject to replacement |
static StringBuilder replaceStr(StringBuilder original, char replacementChar, Stream<String> stringsToReplace)
//package com.java2s; /*//w ww. j a v a 2 s. c om * Copyright 2017 Johns Hopkins University * * 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. */ import java.util.stream.Stream; public class Main { /** * Replaces the occurrence of each string in {@code stringsToReplace} with the {@code replacementChar} * in the {@code original} string. * <p> * Examples: * </p> * <p> * original: "foo" * replacementChar: 'X' * stringsToReplace: { "baz" } * result: "foo" * The string "baz" never appears in the original string. * </p> * <p> * original: "foo" * replacementChar: 'X' * stringsToReplace: { "o" } * result: "fXX" * The string "o" occurs twice in the original string. * </p> * <p> * original: "foo" * replacementChar: 'X' * stringsToReplace: { "fo" } * result: "XXo" * The string "fo" occurs once in the original string. * </p> * <p> * original: "foo" * replacementChar: 'X' * stringsToReplace: { "of" } * result: "foo" * The string "of" never appears in the original string * </p> * * @param original the string to perform a replacement on * @param replacementChar the character used to replace each character of a matching string * @param stringsToReplace strings that may appear in the original string which are subject to replacement * @return the {@code original} StringBuilder instance, which may have had a replacement operation performed on it */ static StringBuilder replaceStr(StringBuilder original, char replacementChar, Stream<String> stringsToReplace) { stringsToReplace.forEach(toReplace -> { int index = -1; while ((index = original.indexOf(toReplace)) > -1) { for (int replacementIndex = index; replacementIndex < (index + toReplace.length()); replacementIndex++) { original.setCharAt(replacementIndex, replacementChar); } } }); return original; } }