⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 stringutil.java

📁 这是一个基于java编写的torrent的P2P源码
💻 JAVA
📖 第 1 页 / 共 4 页
字号:
// ===========================================================================
// CONTENT  : CLASS StringUtil
// AUTHOR   : Manfred Duchrow
// VERSION  : 2.0 - 21/03/2003
// HISTORY  :
//  10/07/1999 	duma  CREATED
//	09/12/1999	duma	added		->	SPACE, repeat()
//										moved		->	from package com.mdcs.util
//	25/01/2000	duma	moved		->	from package com.mdcs.text
//  09/02/2000  duma  changed ->  renamed SPACE to CH_SPACE
//                    added   ->  CH_CR, CH_TAB, ..., STR_SPACE, STR_NEWLINE, ...
//  11/01/2002  duma  added   ->	indexOf(), indexOfIgnoreCase(), contains(), containsIgnoreCase()
//	17/05/2002	duma	added		->	copyFrom()
//	03/07/2002	duma	added		->	cutHead(), prefix(), suffix()
//	06/07/2002	duma	added		->	indexOf() and contains() for StringPattern and reverse()
//	15/08/2002	duma	added		->	upTo(), startingFrom(), asMap()
//	29/09/2002	duma	added		->	allParts() and allSubstrings() that don't skip empty elements
//	06/03/2003	duma	changed	->	append() now uses System.arraycopy()
//										added		->	remove( String[], String[] ), remove( String[], String )
//																removeNull( String[] )
//	21/03/2003	duma	added		->	leftPad(), leftPadCh(), rightPad(), rightPadCh() for int values
//
// Copyright (c) 1999-2003, by Manfred Duchrow. All rights reserved.
// ===========================================================================
package org.pf.text;

// ===========================================================================
// IMPORT
// ===========================================================================
import java.text.CharacterIterator;
import java.text.StringCharacterIterator;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.StringTokenizer;
import java.util.ArrayList;
import java.io.PrintWriter;
import java.io.StringWriter;

/**
 * The sole instance of this class provides several convienience methods
 * for string manipulation such as substring replacement or character repetition.
 *
 * @author Manfred Duchrow
 * @version 2.0
 */
public class StringUtil
{
  // =========================================================================
  // CONSTANTS
  // =========================================================================
  /** Constant for the space character **/
	public static final char CH_SPACE					= '\u0020' ;
	/** Constant for the new line character **/
	public static final char CH_NEWLINE  			= '\n' ;
	/** Constant for the carriage return character **/
	public static final char CH_CR  			    = '\r' ;
	/** Constant for the tabulator character **/
	public static final char CH_TAB     			= '\t' ;

	/** Constant for the String representation of the space character **/
	public static final String STR_SPACE			= "\u0020" ;
	/** Constant for the String representation of the new line character **/
	public static final String STR_NEWLINE  	= "\n" ;
	/** Constant for the String representation of the carriage return character **/
	public static final String STR_CR  			  = "\r" ;
	/** Constant for the String representation of the tabulator character **/
	public static final String STR_TAB     		= "\t" ;

  private static final String WORD_DELIM    = STR_SPACE + STR_TAB
											+ STR_NEWLINE + STR_CR ;

  // =========================================================================
  // CLASS VARIABLES
  // =========================================================================
  private static StringUtil singleton = null ;
  private static StringUtil getSingleton() { return singleton ; }
  private static void setSingleton( StringUtil inst ) { singleton = inst ; }

  // =========================================================================
  // PUBLIC CLASS METHODS
  // =========================================================================
  /**
   * Returns the one and only instance of this class.
   */
  public static StringUtil current()
  {
    if ( getSingleton() == null )
      setSingleton( new StringUtil() ) ;
    return getSingleton() ;
  } // current()

  // =========================================================================
  // PUBLIC INSTANCE METHODS
  // =========================================================================
  /**
   * Returns the given string with all found oldSubStr replaced by newSubStr.   <br>
   *
   * Example: StringUtil.current().replaceAll( "Seven of ten", "even", "ix" ) ;<br>
   * results in: "Six of ten"
   *
   * @param sourceStr The string that should be checked for occurrences of oldSubStr
   * @param oldSubStr The string that is searched for in sourceStr
   * @param newSubStr The new string that is placed everywhere the oldSubStr was found
   * @return The original string with all found substrings replaced by new strings
   */
  public String replaceAll( String sourceStr, String oldSubStr, String newSubStr )
  {
    String part     = null ;
    String result   = "" ;
    int index       = -1 ;
    int subLen      = 0 ;

    subLen = oldSubStr.length() ;
    part = sourceStr ;
    while ( ( part.length() > 0 ) && ( subLen > 0 ) )
    {
      index = part.indexOf( oldSubStr ) ;
      if ( index >= 0 )
      {
        result = result + part.substring( 0, index ) + newSubStr ;
        part = part.substring( index + subLen ) ;
      }
      else
      {
        result = result + part ;
        part = "" ;
      }
    } // while

    return result ;
  } // replaceAll()

  // -------------------------------------------------------------------------

	/**
	 * Returns a string with size of count and all characters initialized with ch.   <br>
	 *
	 * @param ch the character to be repeated in the result string.
	 * @param count the number of times the given character should occur in the result string.
	 * @return A string containing <i>count</i> characters <i>ch</i>.
	 */
	public String repeat( char ch, int count )
	{
		StringBuffer buffer		= null ;

		buffer = new StringBuffer( count ) ;
		for ( int i = 1 ; i <= count ; i++ )
		{
			buffer.append( ch ) ;
		}

		return ( buffer.toString() ) ;
	} // repeat()

  // -------------------------------------------------------------------------

  /**
   * Returns an array of substrings of the given text.    <br>
   * The delimiters between the substrings are the whitespace characters
   * SPACE, NEWLINE, CR and TAB.
   *
   * @see #parts(String, String)
   * @param text The string that should be splitted into whitespace separated words
   * @return An array of substrings of the given text
   */
  public String[] words( String text )
  {
  	return this.parts( text, WORD_DELIM ) ;
  } // words()

  // -------------------------------------------------------------------------

  /**
   * Returns an array of substrings of the given text.    <br>
   * The separators between the substrings are the given delimiters.
   * Each character in the delimiter string is treated as a separator.
   * <br>
   * All consecutive delimiters are treated as one delimiter, that is there
   * will be no empty strings in the result.
   *
   * @see #allParts(String, String)
   * @see #substrings(String, String)
   * @see #allSubstrings(String, String)
   * @param text The string that should be splitted into substrings
   * @param delimiters All characters that should be recognized as a separator or substrings
   * @return An array of substrings of the given text
   */
  public String[] parts( String text, String delimiters )
  {
    return this.parts( text, delimiters, false ) ;
  } // parts()

  // -------------------------------------------------------------------------

  /**
   * Returns an array of substrings of the given text.    <br>
   * The separators between the substrings are the given delimiters.
   * Each character in the delimiter string is treated as a separator.
   * <br>
   * For each delimiter that is followed immediately by another delimiter an
   * empty string will be added to the result. There are no empty strings added
   * to the result for a delimiter at the very beginning of at the very end.
   * <p>
   * Examples:
   * <p>
   * allParts( "/A/B//", "/" )  --> { "A", "B", "" }     <br>
   * allParts( "/A,B/C;D", ",;/" )  --> { "A", "B", "C", "D" }     <br>
   * allParts( "A/B,C/D", "," )  --> { "A/B", "C/D" }     <br>
   *
   * @see #parts(String, String)
   * @see #substrings(String, String)
   * @see #allSubstrings(String, String)
   * @param text The string that should be splitted into substrings
   * @param delimiters All characters that should be recognized as a separator or substrings
   * @return An array of substrings of the given text
   */
  public String[] allParts( String text, String delimiters )
  {
    return this.parts( text, delimiters, true ) ;
  } // allParts()

  // -------------------------------------------------------------------------

	/**
	 * Returns the given text split up into an array of strings, at
	 * the occurrances of the separator string.
	 * 
	 * In contrary to method parts() the separator is a one or many
	 * character sequence delimiter. That is, only the exact sequence 
	 * of the characters in separator identifies the end of a substring.
	 * Subsequent occurences of separator will be skipped. Therefore
	 * no empty strings ("") will be in the result array.
	 * 
	 * @see #allSubstrings(String, String)
	 * @see #parts(String, String)
	 * @see #allParts(String, String)
	 * @param text The text to be split up
	 * @param separator The string that separates the substrings
	 * @return An array of substrings not containing any separator anymore
	 */
  public String[] substrings( String text, String separator )
  {
		return this.substrings( text, separator, false ) ;
  } // substrings()

  // -------------------------------------------------------------------------

	/**
	 * Returns the given text split up into an array of strings, at
	 * the occurrances of the separator string.
	 * 
	 * In contrary to method allParts() the separator is a one or many
	 * character sequence delimiter. That is, only the exact sequence 
	 * of the characters in separator identifies the end of a substring.
	 * Subsequent occurences of separator are not skipped. They are added
	 * as empty strings to the result.
	 * 
	 * @see #substrings(String, String)
	 * @see #parts(String, String)
	 * @see #allParts(String, String)
	 * @param text The text to be split up
	 * @param separator The string that separates the substrings
	 * @return An array of substrings not containing any separator anymore
	 */
  public String[] allSubstrings( String text, String separator )
  {
		return this.substrings( text, separator, true ) ;
  } // allSubstrings()

  // -------------------------------------------------------------------------

  /**
   * Returns the first substring that is enclosed by the specified delimiters.  
   * <br>
   * The delimiters are not included in the return string.
   * <p>
   * Example:<br>
   * getDelimitedSubstring( "This {placeholder} belongs to me", "{", "}" )
   * --> returns "placeholder"
   *
   * @param text The input string that contains the delimited part
   * @param startDelimiter The start delimiter of the substring
   * @param endDelimiter The end delimiter of the substring
   * @return The substring or an empty string, if no delimiters are found.
   */
  public String getDelimitedSubstring( String text, String startDelimiter,
  																			String endDelimiter )
  {
    int start ;
    int stop ;
    String subStr   = "" ;

    if ( ( text != null ) && ( startDelimiter != null ) 
    		&& ( endDelimiter != null ) )
    {
      start = text.indexOf( startDelimiter ) ;
      if ( start >= 0 )
      {
	      stop = text.indexOf( endDelimiter, start + 1 ) ;
	      if ( stop > start )
	        subStr = text.substring( start + 1, stop ) ;
      }
    }

    return subStr ;
  } // getDelimitedSubstring()

  // -------------------------------------------------------------------------

  /**
   * Returns the first substring that is enclosed by the specified delimiter.  <br>
   * The delimiters are not included in the return string.
   * <p>
   * Example:<br>
   * getDelimitedSubstring( "File 'text.txt' not found.", "'", "'" )
   * --> returns "text.txt"
   *
   * @param text The input string that contains the delimited part
   * @param delimiter The start and end delimiter of the substring
   * @return The substring or an empty string, if no delimiters are found.
   */
  public String getDelimitedSubstring( String text, String delimiter )
  {
    return this.getDelimitedSubstring( text, delimiter, delimiter ) ;
  } // getDelimitedSubstring()

  // -------------------------------------------------------------------------

  /**
   * Prints the stack trace of the specified throwable to a
   * string and returns it.
   */
  public String stackTrace( Throwable throwable )
  {
    StringWriter sw   = new StringWriter() ;
    PrintWriter pw    = new PrintWriter( sw ) ;
    throwable.printStackTrace( pw ) ;
    pw.close() ;
    return sw.toString() ;
  } // stackTrace()

  // -------------------------------------------------------------------------

  /**
   * Returns the given string filled (on the left) up to the specified
   * length with the given character.     <br>
   * Example: leftPadCh( "12", 6, '0' ) --> "000012"
   */
  public String leftPadCh( String str, int len, char ch )
  {
    return this.padCh( str, len, ch, true ) ;
  } // leftPadCh()

  // -------------------------------------------------------------------------

  /**
   * Returns the given string filled (on the left) up to the specified
   * length with spaces.     <br>
   * Example: leftPad( "XX", 4 ) --> "  XX"
   * 
   * @param str The string that has to be filled up to the specified length
   * @param len The length of the result string
   */
  public String leftPad( String str, int len )
  {
    return this.leftPadCh( str, len, CH_SPACE ) ;
  } // leftPad()

  // -------------------------------------------------------------------------

  /**
   * Returns the given integer as string filled (on the left) up to the 
   * specified length with the given fill character.     <br>
   * Example: leftPad( 24, 5, '*' ) --> "***24"
   */
  public String leftPadCh( int value, int len, char fillChar )
  {
    return this.leftPadCh( Integer.toString(value), len, fillChar ) ;
  } // leftPadCh()

  // -------------------------------------------------------------------------

  /**
   * Returns the given integer as string filled (on the left) up to the 
   * specified length with zeroes.     <br>
   * Example: leftPad( 12, 4 ) --> "0012"
   */
  public String leftPad( int value, int len )
  {
    return this.leftPadCh( value, len, '0' ) ;
  } // leftPad()

  // -------------------------------------------------------------------------

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -