Как найти количество вхождений подстроки в строку

(PHP 4, PHP 5, PHP 7, PHP 8)

substr_countВозвращает число вхождений подстроки

Описание

substr_count(
    string $haystack,
    string $needle,
    int $offset = 0,
    ?int $length = null
): int

Замечание:

Эта функция не подсчитывает перекрывающиеся подстроки. Смотрите пример ниже!

Список параметров

haystack

Строка, в которой ведётся поиск

needle

Искомая подстрока

offset

Смещение начала отсчёта. Если задано отрицательное значение, отсчёт позиции
будет произведён с конца строки.

length

Максимальная длина строки, в которой будет производится поиск
подстроки после указанного смещения. Если сумма смещения
и максимальной длины будет больше длины haystack,
то будет выведено предупреждение. Отрицательное значение будет отсчитываться
с конца haystack.

Возвращаемые значения

Эта функция возвращает целое число (int).

Список изменений

Версия Описание
8.0.0 length теперь допускает значение null.
7.1.0 Добавлена поддержка отрицательных значений offset
и length.
length теперь также может быть 0.

Примеры

Пример #1 Пример использования substr_count()


<?php
$text
= 'This is a test';
echo
strlen($text); // 14echo substr_count($text, 'is'); // 2

// строка уменьшается до 's is a test', поэтому вывод будет 1

echo substr_count($text, 'is', 3);// текст уменьшается до 's i', поэтому вывод будет 0
echo substr_count($text, 'is', 3, 3);// генерирует предупреждение, так как 5+10 > 14
echo substr_count($text, 'is', 5, 10);// выводит только 1, т.к. перекрывающиеся подстроки не учитываются
$text2 = 'gcdgcdgcd';
echo
substr_count($text2, 'gcdgcd');
?>

Смотрите также

  • count_chars() — Возвращает информацию о символах, входящих в строку
  • strpos() — Возвращает позицию первого вхождения подстроки
  • substr() — Возвращает подстроку
  • strstr() — Находит первое вхождение подстроки

tuxedobob

7 years ago


It's worth noting this function is surprisingly fast. I first ran it against a ~500KB string on our web server. It found 6 occurrences of the needle I was looking for in 0.0000 seconds. Yes, it ran faster than microtime() could measure.

Looking to give it a challenge, I then ran it on a Mac laptop from 2010 against a 120.5MB string. For one test needle, it found 2385 occurrences in 0.0266 seconds. Another test needs found 290 occurrences in 0.114 seconds.

Long story short, if you're wondering whether this function is slowing down your script, the answer is probably not.


flobi at flobi dot com

16 years ago


Making this case insensitive is easy for anyone who needs this.  Simply convert the haystack and the needle to the same case (upper or lower).

substr_count(strtoupper($haystack), strtoupper($needle))


tweston at bangordailynews dot com

8 years ago


To account for the case that jrhodes has pointed out, we can change the line to:

substr_count ( implode( ',', $haystackArray ), $needle );

This way:

array (
  0 => "mystringth",
  1 => "atislong"
);

Becomes

mystringth,atislong

Which brings the count for $needle = "that" to 0 again.


jrhodes at roket-enterprises dot com

13 years ago


It was suggested to use

substr_count ( implode( $haystackArray ), $needle );

instead of the function described previously, however this has one flaw.  For example this array:

array (
  0 => "mystringth",
  1 => "atislong"
);

If you are counting "that", the implode version will return 1, but the function previously described will return 0.


XinfoX X at X XkarlX X-X XphilippX X dot X XdeX

19 years ago


Yet another reference to the "cgcgcgcgcgcgc" example posted by "chris at pecoraro dot net":

Your request can be fulfilled with the Perl compatible regular expressions and their lookahead and lookbehind features.

The example

$number_of_full_pattern = preg_match_all('/(cgc)/', "cgcgcgcgcgcgcg", $chunks);

works like the substr_count function. The variable $number_of_full_pattern has the value 3, because the default behavior of Perl compatible regular expressions is to consume the characters of the string subject that were matched by the (sub)pattern. That is, the pointer will be moved to the end of the matched substring.
But we can use the lookahead feature that disables the moving of the pointer:

$number_of_full_pattern = preg_match_all('/(cg(?=c))/', "cgcgcgcgcgcgcg", $chunks);

In this case the variable $number_of_full_pattern has the value 6.
Firstly a string "cg" will be matched and the pointer will be moved to the end of this string. Then the regular expression looks ahead whether a 'c' can be matched. Despite of the occurence of the character 'c' the pointer is not moved.


info at fat-fish dot co dot il

16 years ago


a simple version for an array needle (multiply sub-strings):
<?phpfunction substr_count_array( $haystack, $needle ) {
    
$count = 0;
     foreach (
$needle as $substring) {
         
$count += substr_count( $haystack, $substring);
     }
     return
$count;
}
?>

qeremy [atta] gmail [dotta] com

9 years ago


Unicode example with "case-sensitive" option;

<?php
function substr_count_unicode($str, $substr, $caseSensitive = true, $offset = 0, $length = null) {
    if (
$offset) {
       
$str = substr_unicode($str, $offset, $length);
    }
$pattern = $caseSensitive
       
? '~(?:'. preg_quote($substr) .')~u'
       
: '~(?:'. preg_quote($substr) .')~ui';
   
preg_match_all($pattern, $str, $matches);

    return isset(

$matches[0]) ? count($matches[0]) : 0;
}

function

substr_unicode($str, $start, $length = null) {
    return
join('', array_slice(
       
preg_split('~~u', $str, -1, PREG_SPLIT_NO_EMPTY), $start, $length));
}
$s = 'Ümit yüzüm gözüm...';
print
substr_count_unicode($s, 'ü');            // 3
print substr_count_unicode($s, 'ü', false);     // 4
print substr_count_unicode($s, 'ü', false, 10); // 1print substr_count_unicode($s, 'üm');           // 2
print substr_count_unicode($s, 'üm', false);    // 3
?>


php at blink dot at

8 years ago


This will handle a string where it is unknown if comma or period are used as thousand or decimal separator. Only exception where this leads to a conflict is when there is only a single comma or period and 3 possible decimals (123.456 or 123,456). An optional parameter is passed to handle this case (assume thousands, assume decimal, decimal when period, decimal when comma). It assumes an input string in any of the formats listed below.

function toFloat($pString, $seperatorOnConflict="f")
{
    $decSeperator=".";
    $thSeperator="";

    $pString=str_replace(" ", $thSeperator, $pString);

    $firstPeriod=strpos($pString, ".");
    $firstComma=strpos($pString, ",");
    if($firstPeriod!==FALSE && $firstComma!==FALSE) {
        if($firstPeriod<$firstComma) {
            $pString=str_replace(".", $thSeperator, $pString);
            $pString=str_replace(",", $decSeperator, $pString);
        }
        else {
            $pString=str_replace(",", $thSeperator, $pString);
        }
    }
    else if($firstPeriod!==FALSE || $firstComma!==FALSE) {
        $seperator=$firstPeriod!==FALSE?".":",";
        if(substr_count($pString, $seperator)==1) {
            $lastPeriodOrComma=strpos($pString, $seperator);
            if($lastPeriodOrComma==(strlen($pString)-4) && ($seperatorOnConflict!=$seperator && $seperatorOnConflict!="f")) {
                $pString=str_replace($seperator, $thSeperator, $pString);
            }
            else {
                $pString=str_replace($seperator, $decSeperator, $pString);
            }
        }
        else {
            $pString=str_replace($seperator, $thSeperator, $pString);
        }
    }
    return(float)$pString;
}

function testFloatParsing() {
    $floatvals = array(
        "22 000",
        "22,000",
        "22.000",
        "123 456",
        "123,456",
        "123.456",
        "22 000,76",
        "22.000,76",
        "22,000.76",
        "22000.76",
        "22000,76",
        "1.022.000,76",
        "1,022,000.76",
        "1,000,000",
        "1.000.000",
        "1022000.76",
        "1022000,76",
        "1022000",
        "0.76",
        "0,76",
        "0.00",
        "0,00",
        "1.00",
        "1,00",
        "-22 000,76",
        "-22.000,76",
        "-22,000.76",
        "-22 000",
        "-22,000",
        "-22.000",
        "-22000.76",
        "-22000,76",
        "-1.022.000,76",
        "-1,022,000.76",
        "-1,000,000",
        "-1.000.000",
        "-1022000.76",
        "-1022000,76",
        "-1022000",
        "-0.76",
        "-0,76",
        "-0.00",
        "-0,00",
        "-1.00",
        "-1,00"
    );

        echo "<table>
        <tr>
            <th>String</th>
            <th>thousands</th>
            <th>fraction</th>
            <th>dec. if period</th>
            <th>dec. if comma</th>
        </tr>";

            foreach ($floatvals as $fval) {
        echo "<tr>";
        echo "<td>" . (string) $fval . "</td>";

                echo "<td>" . (float) toFloat($fval, "") . "</td>";
        echo "<td>" . (float) toFloat($fval, "f") . "</td>";
        echo "<td>" . (float) toFloat($fval, ".") . "</td>";
        echo "<td>" . (float) toFloat($fval, ",") . "</td>";
        echo "</tr>";
    }
    echo "</table>";
}


gigi at phpmycoder dot com

14 years ago


below was suggested a function for substr_count'ing an array, yet for a simpler procedure, use the following:

<?php
substr_count
( implode( $haystackArray ), $needle );
?>


chrisstocktonaz at gmail dot com

13 years ago


In regards to anyone thinking of using code contributed by zmindster at gmail dot com

Please take careful consideration of possible edge cases with that regex, in example:

$url = 'http://w3.host.tld/path/to/file/..../file.extension';
$url = 'http://w3.host.tld/path/to/file/../file.extension?malicous=....';

This would cause a infinite loop and for example be a possible entry point for a denial of service attack. A correct fix would require additional code, a quick hack would be just adding a additional check, without clarity or performance in mind:

...
$i = 0;
while (substr_count($url, '../') && ++$i < strlen($url))
...

-Chris


The current best answer involving method count doesn’t really count for overlapping occurrences and doesn’t care about empty sub-strings as well.
For example:

>>> a = 'caatatab'
>>> b = 'ata'
>>> print(a.count(b)) #overlapping
1
>>>print(a.count('')) #empty string
9

The first answer should be 2 not 1, if we consider the overlapping substrings.
As for the second answer it’s better if an empty sub-string returns 0 as the asnwer.

The following code takes care of these things.

def num_of_patterns(astr,pattern):
    astr, pattern = astr.strip(), pattern.strip()
    if pattern == '': return 0

    ind, count, start_flag = 0,0,0
    while True:
        try:
            if start_flag == 0:
                ind = astr.index(pattern)
                start_flag = 1
            else:
                ind += 1 + astr[ind+1:].index(pattern)
            count += 1
        except:
            break
    return count

Now when we run it:

>>>num_of_patterns('caatatab', 'ata') #overlapping
2
>>>num_of_patterns('caatatab', '') #empty string
0
>>>num_of_patterns('abcdabcva','ab') #normal
2

Задачу можно решить с помощью алгоритма Кнута-Морриса-Пратта

Пусть у нас есть искомая подстрока substring, исходная строка str, и символ-разделитель, такой что он не входит ни в substring, ни в str. Тогда мы можем составить строку вида:
substring + разделитель + str и пройтись по ней префикс-функцией:

Привожу код на Java, думаю что вам не составит труда переписать его на C#

public static void main(String args []) {
    String str = "AByrjujABw qr";
    String substring = "AB";
    String full = substring + "#" + str;
    int[] prefix = prefix(full.toCharArray());
    System.out.println(Arrays.toString(prefix));
}

private static int[] prefix(char[] s){
    int n = s.length;
    int[] pi = new int[n];
    for (int i = 1; i < n; ++i) {
        int j = pi[i-1];
        while (j > 0 && s[i] != s[j])
            j = pi[j-1];
        if (s[i] == s[j])  ++j;
        pi[i] = j;
    }
    return pi;
}

После прохода префикс-функцией вам нужно пройтись по массиву prefix и посчитать количество чисел, равных длине вашей искомой подстроки, это и будет ответом.

Результат выполнения префикс-функции:

[0, 0, 0, 1, 2, 0, 0, 0, 0, 0, 1, 2, 0, 0, 0, 0]

длина искомой подстроки — 2, число 2 в префиксном массиве встречается 2 раза.

Обратите внимание, что алгоритм даст результат при пересечении подстрок, например имея строки:

str = "ABAxxABABAyy";
substring = "ABA";

результат будет равен 3, так как ABA встречается фактически 3 раза, 2 из которых пересекаются (подстрока ABABA)

Метод count() строки возвращает количество вхождений подстроки в заданной строке.

Проще говоря, метод ищет подстроку в заданной строке и возвращает, сколько раз подстрока присутствует в ней.

Также требуются необязательные параметры start и end, чтобы указать соответственно начальную и конечную позиции в строке.

Синтаксис метода:

string.count(substring, start=..., end=...)

Параметры

Метод требует для выполнения только одного параметра. Однако у него также есть два необязательных параметра:

  • substring ‒ строка, количество которой нужно найти.
  • start (необязательно) ‒ начальный индекс в строке, с которой начинается поиск.
  • end (необязательно) ‒ конечный индекс в строке, где заканчивается поиск.

Примечание: Индекс в Python начинается с 0, а не с 1.

Возвращаемое значение

Команда возвращает количество вхождений подстроки в заданной строке.

Пример 1: Подсчитать количество вхождений данной подстроки

# define string
string = "Python is awesome, isn't it?"
substring = "is"

count = string.count(substring)

# print count
print("The count is:", count)

Выход

The count is: 2

Пример 2: Подсчитать количество появлений данной подстроки, используя начало и конец

# define string
string = "Python is awesome, isn't it?"
substring = "i"

# count after first 'i' and before the last 'i'
count = string.count(substring, 8, 25)

# print count
print("The count is:", count)

Выход

The count is: 1

Здесь подсчет начинается после того, как будет обнаружен первый i, то есть седьмая позиция индекса. И он заканчивается перед последним i, то есть 25-й позицией индекса.

56245cookie-checkМетод string count() в Python

1 / 1 / 0

Регистрация: 22.11.2009

Сообщений: 37

1

Как подсчитать количество вхождений подстроки в строку

16.01.2011, 20:03. Показов 64025. Ответов 7


Студворк — интернет-сервис помощи студентам

Добрый вечер! Как можно подсчитать количество вхождений строки S2 в строку S1?

Допустим:

S1= dfsgsffgsrr
S2= gs



0



sandye51

программист С++

841 / 600 / 147

Регистрация: 19.12.2010

Сообщений: 2,014

16.01.2011, 20:07

2

Rooney,

C
1
2
3
4
5
6
7
int c = 0;
char* p = strstr(string, substring);
while (p)
{
c++;
p = strstr(string, substring); 
}



0



asics

Freelance

Эксперт С++

2889 / 1824 / 356

Регистрация: 09.09.2010

Сообщений: 3,841

16.01.2011, 20:11

3

Лучший ответ Сообщение было отмечено mik-a-el как решение

Решение

Rooney,

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
#include <string>
 
int main()
{
    std::string s1("dffffsgsffgsrr"), s2("ff");
    size_t cnt = 0;
 
    for(std::string::size_type i = 0; i < s1.length(); ++i)
        if(s1[i] == s2[0])
            if(s1.substr(i, s2.length()) == s2)
            {
                ++cnt;
                i += s2.length() - 1;
            }
 
    std::cout << cnt;
    return 0;
}



1



Rooney

1 / 1 / 0

Регистрация: 22.11.2009

Сообщений: 37

16.01.2011, 20:25

 [ТС]

4

Не могли бы помочь, через массив решить…

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <iostream>
#include <windows.h>
#include <fstream>
#include <string>
 
using namespace std;
 
int main()
{
    SetConsoleCP(1251);
    SetConsoleOutputCP(1251);
    const int S = 256;    
    char s1[S] = "";
    char s2[S] = "";
    cout << "Введите строку S1:";
    cin.getline(s1,S);
    cout << "Строка: [" << s1 << "] n";
    cout << "Введите строку S2:";
    cin.getline(s2,S);
    cout << "Строка: [" << s2 << "] n";
   
   
   
     system ("pause"); 
     return 0;
}



0



asics

Freelance

Эксперт С++

2889 / 1824 / 356

Регистрация: 09.09.2010

Сообщений: 3,841

16.01.2011, 20:34

5

Rooney,

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#include <iostream>
#include <windows.h>
#include <fstream>
#include <cstring>
 
using namespace std;
 
int main()
{
    SetConsoleCP(1251);
    SetConsoleOutputCP(1251);
    const int S = 256;
    int k, cnt = 0;
    char s1[S] = "";
    char s2[S] = "";
    cin.getline(s1,S);
    cin.getline(s2,S);
 
    for(int i = 0; i < strlen(s1); ++i)
    {
        char tmp[S] = "";
        k = 0;
        if(s1[i] == s2[0])
        {
            for(int j = i; j <= strlen(s2); ++i)
                tmp[k++] = s1[j];
 
            if(strcmp(s2, tmp))
                ++cnt;
                
            i += strlen(s2) - 1;
        }
    }
 
    cout << cnt;
     return 0;
}



0



1 / 1 / 0

Регистрация: 22.11.2009

Сообщений: 37

16.01.2011, 20:50

 [ТС]

6

Последний вариант не компилируется



0



Freelance

Эксперт С++

2889 / 1824 / 356

Регистрация: 09.09.2010

Сообщений: 3,841

16.01.2011, 21:16

7

Rooney, Ну ниче не поделаеш, я ж незнаю какие ошибки выдает, у меня все хорошо скомпилировалось.



0



Rooney

1 / 1 / 0

Регистрация: 22.11.2009

Сообщений: 37

17.01.2011, 18:40

 [ТС]

8

Попытался переделать…

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#include <iostream>
#include <windows.h>
#include <fstream>
 
using namespace std;
 
int main()
{
        SetConsoleCP(1251);
        SetConsoleOutputCP(1251);
        const int S = 256; 
        char a[S] = "";
        char b[S] = "";
        int k = 0,cnt = 0;
        cout << "Ââåäèòå ñòðîêó 1:"<< endl;
        cin.getline(a,S);
        cout << "Ñòðîêà: [" << a << "] n";
        cout << "Ââåäèòå ñòðîêó 2:"<< endl;
        cin.getline(b,S);
        int const la = strlen(a);
        int const lb = strlen(b);
        cout << "Ñòðîêà: [" << b << "] n";
        for(int i =0 ; i < la; i++){
                char tmp[S] = "";
                k=0;
                if(a[i] == b[0]){
                    for(int j=i; j<=lb ;j++){
                        tmp[k] = a[j];
                        k++;
                    }
                    if(strcmp(b,tmp))cnt++;
                }
        }    
        cout << "Êîëè÷åñòâî âõîæäåíèé: " << cnt << endl;
        system ("pause"); 
        return 0;
}

Проблема в том что,
прога не отличает строку «привет» от «привед»… засчитывает как вхождение…

Добавлено через 5 часов 15 минут
Нашёл решение самостоятельно:

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#include <iostream>
#include <windows.h>
#include <fstream>
#include <cstring>
using namespace std;
 
int main()
{
        SetConsoleCP(1251);
        SetConsoleOutputCP(1251);
        const int S = 256; 
        char a[S] = "";
        char b[S] = "";
        int k = 0,cnt = 0;
        cout << "Введите строку 1:"<< endl;
        cin.getline(a,S);
        cout << "Строка: [" << a << "] n";
        cout << "Введите строку 2:"<< endl;
        cin.getline(b,S);
        int const la = strlen(a);
        int const lb = strlen(b);
        cout << "Строка: [" << b << "] n";
        for(int i =0 ; i < la; i++){
                char tmp[S] = "";
                k=0;
                if(a[i] == b[0]){
                    int j = i;
                    while(a[j] == b[k]){
                        tmp[k] = a[j];
                        j++; k++;
                    }
                    if(!(strcmp(b,tmp)))cnt++;
                }
        }    
        cout << "Количество вхождений: " << cnt << endl;
        system ("pause"); 
        return 0;
}



1



Понравилась статья? Поделить с друзьями:
  • Как найти массу с помощью силы тяжести
  • Как найти банк инвестор
  • Как составить структуру характера
  • Циклическая частота как найти период
  • Как составить вертикальную диаграмму