replace a string by another string - Android java.lang

Android examples for java.lang:String Replace

Description

replace a string by another string

Demo Code

public class Main {
  public static final String EMPTY = "";

  public static void main(String[] argv) {
    String text = "java2s.com";
    String repl = "o";
    String with = "0";
    System.out.println(replace(text, repl, with));
  }//ww w  .j av a  2s  .c om

  public static String replace(String text, String repl, String with) {
    return replace(text, repl, with, -1);
  }

  public static boolean isEmpty(String str) {
    return str == null || str.length() == 0;
  }

  public static String replace(String text, String repl, String with, int max) {
    if (isEmpty(text) || isEmpty(repl) || with == null || max == 0) {
      return text;
    }
    int start = 0;
    int end = text.indexOf(repl, start);
    if (end == -1) {
      return text;
    }
    int replLength = repl.length();
    int increase = with.length() - replLength;
    increase = (increase < 0 ? 0 : increase);
    increase *= (max < 0 ? 16 : (max > 64 ? 64 : max));
    StringBuffer buf = new StringBuffer(text.length() + increase);
    while (end != -1) {
      buf.append(text.substring(start, end)).append(with);
      start = end + replLength;
      if (--max == 0) {
        break;
      }
      end = text.indexOf(repl, start);
    }
    buf.append(text.substring(start));
    return buf.toString();
  }

  public static int indexOf(String str, char searchChar) {
    if (isEmpty(str)) {
      return -1;
    }
    return str.indexOf(searchChar);
  }

  public static String substring(String str, int start, int end) {
    if (str == null) {
      return null;
    }

    // handle negatives
    if (end < 0) {
      end = str.length() + end; // remember end is negative
    }
    if (start < 0) {
      start = str.length() + start; // remember start is negative
    }

    // check length next
    if (end > str.length()) {
      end = str.length();
    }

    // if start is greater than end, return ""
    if (start > end) {
      return EMPTY;
    }
    if (start < 0) {
      start = 0;
    }
    if (end < 0) {
      end = 0;
    }
    return str.substring(start, end);
  }

  public static String substring(String str, int start) {
    if (str == null) {
      return null;
    }

    // handle negatives, which means last n characters
    if (start < 0) {
      start = str.length() + start; // remember start is negative
    }
    if (start < 0) {
      start = 0;
    }
    if (start > str.length()) {
      return EMPTY;
    }
    return str.substring(start);
  }

}

Related Tutorials