Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

C Exercise 96

C Exercise 96

100 Classic C Language Examples 100 Classic C Language Examples

**Problem:** Count the number of occurrences of a substring in a string.

**Analysis:** None.

Example

// Created by www.runoob.com on 15/11/9.

// Copyright (c) 2015 Runoob Tutorial. All rights reserved.

//

#include

<

stdio.h

#include

<

stdlib.h

#include

<

string.h

int

main

(

)

{

int

i

,

j

,

k

,

TLen

,

PLen

,

count

=

0

;

char

T

[

50

]

,

P

[

10

]

;

printf

(

"

Please enter two strings separated by Enter, with the main string first and the substring second:

\

n

"

)

;

gets

(

T

)

;

gets

(

P

)

;

TLen

=

strlen

(

T

)

;

PLen

=

strlen

(

P

)

;

for

(

i

=

0

;

i

<=

TLen

PLen

;

i

++

)

{

for

(

j

=

0

,

k

=

i

;

j

<

PLen

&&

P

[

j

]

==

T

[

k

]

;

j

++,

k

++

)

;

if

(

j

==

PLen

)

count

++;

}

printf

(

"

%d

\

n

"

,

count

)

;

system

(

"

pause

"

)

;

return

0

;

}

The above example produces the following output:



Please enter two strings, separated by a newline, with the main string first and the substring second:

abca

a

2

100 Classic C Language Examples 100 Classic C Language Examples