Java String retain characters(remove not in)

Description

Java String retain characters(remove not in)

//package com.demo2s;

public class Main {
  public static void main(String[] argv) throws Exception {
    String str = "demo2s.com demo2s.com";
    String retainChars = "demo";
    System.out.println(retainAllChars(str, retainChars));
  }/*  w w  w.j av a2s.com*/

  /**
   * Removes all characters from 'str' that are not in 'retainChars'. Example:
   * retainAllChars("Hello, world!", "lo") returns "llool"
   */
  public static String retainAllChars(String str, String retainChars) {
    int pos = indexOfChars(str, retainChars);
    if (pos == -1) {
      return "";
    }
    StringBuilder buf = new StringBuilder();
    do {
      buf.append(str.charAt(pos));
      pos = indexOfChars(str, retainChars, pos + 1);
    } while (pos != -1);
    return buf.toString();
  }

  /**
   * Like String.indexOf() except that it will look for any of the characters in
   * 'chars' (similar to C's strpbrk)
   */
  public static int indexOfChars(String str, String chars, int fromIndex) {
    final int len = str.length();

    for (int pos = fromIndex; pos < len; pos++) {
      if (chars.indexOf(str.charAt(pos)) >= 0) {
        return pos;
      }
    }

    return -1;
  }

  /**
   * Like String.indexOf() except that it will look for any of the characters in
   * 'chars' (similar to C's strpbrk)
   */
  public static int indexOfChars(String str, String chars) {
    return indexOfChars(str, chars, 0);
  }

}



PreviousNext

Related