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

C Language Examples - Counting the Occurrences of a Character in a String

C Language Examples - Counting the Occurrences of a Character in a String

C Language Examples C Language Examples

Find the starting position of a character in a string (index starts from 0).

Example

#include

<

stdio.h

int

main

(

)

{

char

str

[

1000

]

,

ch

;

int

i

,

frequency

=

0

;

printf

(

"

Enter a string:

"

)

;

fgets

(

str

,

(

sizeof

str

/

sizeof

str

[

0

]

)

,

stdin

)

;

printf

(

"

Enter the character to search for:

"

)

;

scanf

(

"

%c

"

,&

ch

)

;

for

(

i

=

0

;

str

[

i

]

!= '\

0

'; ++

i

)

{

if

(

ch

==

str

[

i

]

)

++

frequency

;

}

printf

(

"

The number of times character %c appears in the string is %d

"

,

ch

,

frequency

)

;

return

0

;

}

The output is:



输入字符串: runoob

输入要查找的字符: o

字符 o 在字符串中出现的次数为 2

C Language Examples C Language Examples