|
| 1 | +package com.rampatra.strings; |
| 2 | + |
| 3 | +import com.sun.tools.javac.util.Assert; |
| 4 | + |
| 5 | +/** |
| 6 | + * Given two strings, base and remove, return a version of the base string where all instances |
| 7 | + * of the remove string have been removed (not case sensitive). You may assume that the remove |
| 8 | + * string is length 1 or more. Remove only non-overlapping instances, so with "xxx" removing |
| 9 | + * "xx" leaves "x". |
| 10 | + * |
| 11 | + * @author rampatra |
| 12 | + * @since 2019-01-23 |
| 13 | + */ |
| 14 | +public class WithoutString { |
| 15 | + |
| 16 | + public static String withoutString(String base, String remove) { |
| 17 | + String original = base; |
| 18 | + base = base.toLowerCase(); |
| 19 | + remove = remove.toLowerCase(); |
| 20 | + int baseLen = base.length(); |
| 21 | + int removeLen = remove.length(); |
| 22 | + StringBuilder sb = new StringBuilder(); |
| 23 | + |
| 24 | + for (int i = 0; i < baseLen; ) { |
| 25 | + int j = 0; |
| 26 | + // when we see a match, advance the pointer |
| 27 | + if (base.charAt(i) == remove.charAt(0)) { |
| 28 | + while (j < removeLen && i + j < baseLen && base.charAt(i + j) == remove.charAt(j)) { |
| 29 | + j++; |
| 30 | + } |
| 31 | + } |
| 32 | + if (j == removeLen) { // an entire match was found, move ahead and skip these chars |
| 33 | + i += removeLen; |
| 34 | + } else { |
| 35 | + sb.append(original.charAt(i)); // entire match was not found so append the char to StringBuilder |
| 36 | + i++; |
| 37 | + } |
| 38 | + } |
| 39 | + return sb.toString(); |
| 40 | + } |
| 41 | + |
| 42 | + public static void main(String[] args) { |
| 43 | + Assert.check(withoutString("Hello there", "llo").equals("He there")); |
| 44 | + Assert.check(withoutString("THIS is a FISH", "is").equals("TH a FH")); |
| 45 | + Assert.check(withoutString("xxx", "x").equals("")); |
| 46 | + } |
| 47 | +} |
0 commit comments