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

📄 stringutil.java

📁 JSP聊天系统
💻 JAVA
字号:
package org.ehotsoft.yekki.util;

import java.io.PrintStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;

public final class StringUtil {

    private static Object initLock = new Object();
    
	private StringUtil() {
	
	}

    public static final String replace( String line, String oldString, String newString )
    {
        if (line == null) {
            return null;
        }
        int i=0;
        if ( ( i=line.indexOf( oldString, i ) ) >= 0 ) {
            char [] line2 = line.toCharArray();
            char [] newString2 = newString.toCharArray();
            int oLength = oldString.length();
            StringBuffer buf = new StringBuffer(line2.length);
            buf.append(line2, 0, i).append(newString2);
            i += oLength;
            int j = i;
            while( ( i=line.indexOf( oldString, i ) ) > 0 ) {
                buf.append(line2, j, i-j).append(newString2);
                i += oLength;
                j = i;
            }
            buf.append(line2, j, line2.length - j);
            return buf.toString();
        }
        return line;
    }

   public static final String replaceIgnoreCase(String line, String oldString,
            String newString)
    {
        if (line == null) {
            return null;
        }
        String lcLine = line.toLowerCase();
        String lcOldString = oldString.toLowerCase();
        int i=0;
        if ( ( i=lcLine.indexOf( lcOldString, i ) ) >= 0 ) {
            char [] line2 = line.toCharArray();
            char [] newString2 = newString.toCharArray();
            int oLength = oldString.length();
            StringBuffer buf = new StringBuffer(line2.length);
            buf.append(line2, 0, i).append(newString2);
            i += oLength;
            int j = i;
            while( ( i=lcLine.indexOf( lcOldString, i ) ) > 0 ) {
                buf.append(line2, j, i-j).append(newString2);
                i += oLength;
                j = i;
            }
            buf.append(line2, j, line2.length - j);
            return buf.toString();
        }
        return line;
    }

   public static final String replace( String line, String oldString,
            String newString, int[] count)
    {
        if (line == null) {
            return null;
        }
        int i=0;
        if ( ( i=line.indexOf( oldString, i ) ) >= 0 ) {
            int counter = 0;
            counter++;
            char [] line2 = line.toCharArray();
            char [] newString2 = newString.toCharArray();
            int oLength = oldString.length();
            StringBuffer buf = new StringBuffer(line2.length);
            buf.append(line2, 0, i).append(newString2);
            i += oLength;
            int j = i;
            while( ( i=line.indexOf( oldString, i ) ) > 0 ) {
                counter++;
                buf.append(line2, j, i-j).append(newString2);
                i += oLength;
                j = i;
            }
            buf.append(line2, j, line2.length - j);
            count[0] = counter;
            return buf.toString();
        }
        return line;
    }

    public static final String escapeHTMLTags( String input ) {
        
		if( input == null || input.length() == 0 ) {
            return input;
        }
        
		StringBuffer buf = new StringBuffer(input.length());
        
		char ch = ' ';
        for( int i=0; i<input.length(); i++ ) {
            ch = input.charAt(i);
            
			if( ch == '<' )
                buf.append( "&lt;" );
            else if( ch == '>')
                buf.append( "&gt;" );
            else if( ch == '"' )
                buf.append( "&quot;" );
            else if( ch == '&' )
                buf.append( "&amp;" );
            else
                buf.append( ch );
        }
        return buf.toString();
    }
	
	public static final String textToHtml( String input ) {
		
		if( input == null ) return "";
		
		input = replace( input, "\r\n","<p>" );
        input = escapeHTMLTags( input );
		
		StringBuffer buf = new StringBuffer(input.length());
        
		char ch = ' ';

        for( int i=0; i<input.length(); i++ ) {
            ch = input.charAt(i);
            
			if( ch == '\n' )
                buf.append( "<br>" );
            else if( ch == '\t')
                buf.append( "&nbsp;&nbsp;&nbsp;&nbsp" );
            else if( ch == ' ' )
                buf.append( "&nbsp;" );
            else
                buf.append( ch );
        }
      
        return buf.toString();
    }
	
    private static MessageDigest digest = null;

    public synchronized static final String hash(String data) {
        if (digest == null) {
            try {
                digest = MessageDigest.getInstance("MD5");
            }
            catch (NoSuchAlgorithmException nsae) {
                System.err.println("Failed to load the MD5 MessageDigest. " +
                "Jive will be unable to function normally.");
                nsae.printStackTrace();
            }
        }
        digest.update(data.getBytes());
        return toHex(digest.digest());
    }

	public static final String toHex (byte hash[]) {
        StringBuffer buf = new StringBuffer(hash.length * 2);
        int i;

        for (i = 0; i < hash.length; i++) {
            if (((int) hash[i] & 0xff) < 0x10) {
                buf.append("0");
            }
            buf.append(Long.toString((int) hash[i] & 0xff, 16));
        }
        return buf.toString();
    }

   public static final String [] toLowerCaseWordArray(String text) {
        if (text == null || text.length() == 0) {
                return new String[0];
        }
        StringTokenizer tokens = new StringTokenizer(text, " ,\r\n.:/\\+");
        String [] words = new String[tokens.countTokens()];
        for (int i=0; i<words.length; i++) {
            words[i] = tokens.nextToken().toLowerCase();
        }
        return words;
    }

	public static final String[] split( String text ) {
		
		if (text == null || text.length() == 0) {
        
				return new String[0];
        
		}

        StringTokenizer tokens = new StringTokenizer(text, " ,\r\n.:/\\+");
        
		String [] words = new String[tokens.countTokens()];
        
		for (int i=0; i<words.length; i++) {
        
			words[i] = tokens.nextToken().toLowerCase();
        }

        return words;
	}

    /**
     * A list of some of the most common words. For searching and indexing, we
     * often want to filter out these words since they just confuse searches.
     * The list was not created scientifically so may be incomplete :)
     */
    private static final String [] commonWords =  new String [] {
        "a", "and", "as", "at", "be", "do", "i", "if", "in", "is", "it", "so",
        "the", "to"
    };
    private static Map commonWordsMap = null;

    /**
     * Returns a new String array with some of the most common English words
     * removed. The specific words removed are: a, and, as, at, be, do, i, if,
     * in, is, it, so, the, to
     */
    public static final String [] removeCommonWords(String [] words) {
        
		if (commonWordsMap == null) {
            synchronized(initLock) {
                if (commonWordsMap == null) {
                    commonWordsMap = new HashMap();
                    for (int i=0; i<commonWords.length; i++) {
                        commonWordsMap.put(commonWords[i], commonWords[i]);
                    }
                }
            }
        }
       
		ArrayList results = new ArrayList(words.length);
        for (int i=0; i<words.length; i++) {
            if (!commonWordsMap.containsKey(words[i])) {
                results.add(words[i]);
            }
        }
        return (String[])results.toArray(new String[results.size()]);
    }

    private static Random randGen = null;

    private static char[] numbersAndLetters = null;

     public static final String randomString(int length) {
        if (length < 1) {
            return null;
        }
        if (randGen == null) {
            synchronized (initLock) {
                if (randGen == null) {
                    randGen = new Random();
                    numbersAndLetters = ("0123456789abcdefghijklmnopqrstuvwxyz" +
                    "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ").toCharArray();
                }
            }
        }
        char [] randBuffer = new char[length];
        for (int i=0; i<randBuffer.length; i++) {
            randBuffer[i] = numbersAndLetters[randGen.nextInt(71)];
        }
        return new String(randBuffer);
    }

	public static final String chopAtWord(String string, int length) {
        if (string == null) {
            return string;
        }

        char [] charArray = string.toCharArray();
        int sLength = string.length();
        if (length < sLength) {
            sLength = length;
        }

        for (int i=0; i<sLength-1; i++) {
            if (charArray[i] == '\r' && charArray[i+1] == '\n') {
                return string.substring(0, i);
            }
            else if (charArray[i] == '\n') {
                return string.substring(0, i);
            }
        }
        if (charArray[sLength-1] == '\n') {
            return string.substring(0, sLength-1);
        }

        if (string.length() < length) {
            return string;
        }

        for (int i = length-1; i > 0; i--) {
            if (charArray[i] == ' ') {
                return string.substring(0, i).trim();
            }
        }
        return string.substring(0, length);
    }

    /**
     * Highlights words in a string. Words matching ignores case. The actual
     * higlighting method is specified with the start and end higlight tags.
     * Those might be beginning and ending HTML bold tags, or anything else.
     *
     * @param string the String to highlight words in.
     * @param words an array of words that should be highlighted in the string.
     * @param startHighlight the tag that should be inserted to start highlighting.
     * @param endHighlight the tag that should be inserted to end highlighting.
     * @return a new String with the specified words highlighted.
     */
    public static final String highlightWords(String string, String[] words,
        String startHighlight, String endHighlight)
    {
        if (string == null || words == null ||
                startHighlight == null || endHighlight == null)
        {
            return null;
        }

        //Iterate through each word.
        for (int x=0; x<words.length; x++) {
            //we want to ignore case.
            String lcString = string.toLowerCase();
            //using a char [] is more efficient
            char [] string2 = string.toCharArray();
            String word = words[x].toLowerCase();

            //perform specialized replace logic
            int i=0;
            if ( ( i=lcString.indexOf( word, i ) ) >= 0 ) {
                int oLength = word.length();
                StringBuffer buf = new StringBuffer(string2.length);

                //we only want to highlight distinct words and not parts of
                //larger words. The method used below mostly solves this. There
                //are a few cases where it doesn't, but it's close enough.
                boolean startSpace = false;
                char startChar = ' ';
                if (i-1 > 0) {
                    startChar = string2[i-1];
                    if (!Character.isLetter(startChar)) {
                        startSpace = true;
                    }
                }
                boolean endSpace = false;
                char endChar = ' ';
                if (i+oLength<string2.length) {
                    endChar = string2[i+oLength];
                    if (!Character.isLetter(endChar))  {
                        endSpace = true;
                    }
                }
                if ((startSpace && endSpace) || (i==0 && endSpace)) {
                    buf.append(string2, 0, i);
                    if (startSpace && startChar==' ') { buf.append(startChar); }
                    buf.append(startHighlight);
                    buf.append(string2, i, oLength).append(endHighlight);
                    if (endSpace && endChar==' ') { buf.append(endChar); }
                }
                else {
                    buf.append(string2, 0, i);
                    buf.append(string2, i, oLength);
                }

                i += oLength;
                int j = i;
                while( ( i=lcString.indexOf( word, i ) ) > 0 ) {
                    startSpace = false;
                    startChar = string2[i-1];
                    if (!Character.isLetter(startChar)) {
                        startSpace = true;
                    }

                    endSpace = false;
                    if (i+oLength<string2.length) {
                        endChar = string2[i+oLength];
                        if (!Character.isLetter(endChar))  {
                            endSpace = true;
                        }
                    }
                    if ((startSpace && endSpace) || i+oLength==string2.length) {
                        buf.append(string2, j, i-j);
                        if (startSpace && startChar==' ') { buf.append(startChar); }
                        buf.append(startHighlight);
                        buf.append(string2, i, oLength).append(endHighlight);
                        if (endSpace && endChar==' ') { buf.append(endChar); }
                    }
                    else {
                        buf.append(string2, j, i-j);
                        buf.append(string2, i, oLength);
                    }
                    i += oLength;
                    j = i;
                }
                buf.append(string2, j, string2.length - j);
                string = buf.toString();
            }
        }
        return string;
    }

    public static final String escapeForXML(String string) {
       
		if (string == null || string.length() == 0 ) {
            return string;
        }
        char [] sArray = string.toCharArray();
        StringBuffer buf = new StringBuffer(sArray.length);
        char ch;
        for (int i=0; i<sArray.length; i++) {
            ch = sArray[i];
            if(ch == '<') {
                buf.append("&lt;");
            }
            else if (ch == '&') {
                buf.append("&amp;");
            }
            else if (ch == '"') {
                buf.append("&quot;");
            }
            else {
                buf.append(ch);
            }
        }
        return buf.toString();
    }
	

	//debug
	public static String nullToString( String str ) {
		
		return str == null ? "" : str;
	}

}

⌨️ 快捷键说明

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