Advertisement
bobmarley12345

String replace (with escape char)

Jul 4th, 2022
1,007
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. public static String replaceEscapable(String name, char target, char replacement, char escape) {
  2.     StringBuilder sb = new StringBuilder(name.length());
  3.     char prevChar = 0;
  4.     for(int i = 0; i < name.length(); i++) {
  5.         char ch = name.charAt(i);
  6.         if (ch == target) {
  7.             if (prevChar != escape) {
  8.                 sb.append(replacement);
  9.             }
  10.             else {
  11.                 sb.setLength(sb.length() - 1); // subtract escape char
  12.                 sb.append(target);
  13.             }
  14.         }
  15.         else {
  16.             sb.append(ch);
  17.         }
  18.         prevChar = ch;
  19.     }
  20.     return sb.toString();
  21. }
Advertisement
RAW Paste Data Copied
Advertisement