The number of occurrences statistics for a long string in a string

  • Interception string string of occurrences statistics
  • By the replacement string, the string of occurrences statistics
  • Expression, a string of occurrences statistics by positive

 

constxiong.interview Package; 

Import java.util.regex.Matcher; 
Import java.util.regex.Pattern; 

/ * * 
 * count the number of occurrences of a string of a long string 
 * @author ConstXiong 
 * @date 2019-11- 11:01:22 13 is 
 * / 
public  class TestCountWordTimesInText { 

    public  static  void main (string [] args) { 
        string text = " statistical segment length CX CX a string of a string C is now the number of times X CX " ; 
        string Word = " the CX " ; 
        the System. OUT .println (countWordTimesByCutString (text, Word)); 
        . the System OUT.println (countWordTimesByReplace (text, Word)); 
        the System. OUT .println (countWordTimesByRegex (text, Word)); // regular match, wildcard required injection affect the results 
    } 

    / * * 
     * Statistics taken String String occurrence 
     * @param text 
     * @param Word 
     * @return 
     * / 
    public  static  int countWordTimesByCutString (text String, String Word) {
         int times = 0 ;
         IF (!! isEmpty (text) && isEmpty (Word)) { 
            String SubText = text;
             int index = - . 1 ;
            int wordlength = word.length ();
             the while (subText.length ()> wordlength = && (index = subText.indexOf (Word))> - . 1 ) { 
                SubText = subText.substring (index + wordlength); 
                Times ++ ; 
            } 
        } 
        return times; 
    } 
    
    / * * 
     * by substituting a string, the string count occurrences 
     * @param text 
     * @param Word 
     * @return 
     * / 
    public  static  int countWordTimesByReplace (text string, string Word) {
         int times = 0;
         IF (!! IsEmpty (text) && isEmpty (Word)) { 
            Times = (text.length () - text.replace (Word, "" ) .length ()) / word.length (); 
        } 
        return Times; 
    } 
    
    / * * 
     * number of occurrences of regular expressions, statistical string 
     * @param text 
     * @param Word 
     * @return 
     * / 
    public  static  int countWordTimesByRegex (text string, string Word) {
         int times = 0 ;
         IF (isEmpty (! text) &&! isEmpty (Word)) { 
            the Pattern P = Pattern.compile(word);
            Matcher m = p.matcher(text);
            while (m.find()) {
                times++;
            }
        }
        return times;
    }
    
    /**
     * 字符串是否为空
     * @param str
     * @return
     */
    private static boolean isEmpty(String str) {
        return str == null || str.length() == 0;
    }
    
}

 


Description link
 


 

 

Guess you like

Origin www.cnblogs.com/ConstXiong/p/12164934.html