How to obtain the substrings with the most frequent occurrences in a Chinese string

Source: Internet
Author: User
The following is a detailed analysis of the implementation code for obtaining the substrings that appear most frequently in Chinese strings. if you need them, you can refer to the following code directly, you can set the length of a substring (for example, four or five consecutive characters ).

The code is as follows:


$ Str = 'I am a chinese, I am a foreigner, I am a Korean, I am an American, I am a British, I am a chinese, I am a foreigner ';
Count_string ($ str, 5 );
Function Count_string ($ sstr, $ length)
{
$ Cnt_tmp = 0;
$ Cnt = 0;
$ Str = '';
$ Str_tmp = array ();
$ Str_arr = array ();
Mb_internal_encoding ("gb2312 ");
$ Max_length = (mb_strlen ($ sstr)-$ length );

// Obtain the sub-string set
For ($ I = 0; $ I <= $ max_length; $ I ++)
{
$ Str_tmp [] = mb_substr ($ sstr, $ I, $ length );
}
// Remove duplicate substrings
$ Str_tmp = array_unique ($ str_tmp );

// Calculate the number of occurrences
Foreach ($ str_tmp as $ key => $ value)
{
$ Cnt_tmp = mb_substr_count ($ sstr, $ value );
If ($ cnt_tmp >=$ cnt)
{
$ Cnt = $ cnt_tmp;
$ Str_arr [$ value] = $ cnt;
}
}

// Process multiple results
Foreach ($ str_arr as $ key => $ value)
{
If ($ value = $ cnt)
{$ Str. = $ key ."
";}
}

The most frequently occurring substring of echo is:
'. $ Str .'
Number of occurrences: '. $ cnt;
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.