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

C Language Examples - Count Various Characters in a String

C Language Examples - Count Various Characters in a String

C Language Examples C Language Examples

Count the vowels, consonants, digits, and whitespace characters in a string.

Example

#include

<

stdio.h

int

main

(

)

{

char

line

[

150

]

;

int

i

,

vowels

,

consonants

,

digits

,

spaces

;

vowels

=

consonants

=

digits

=

spaces

=

0

;

printf

(

"

Enter a string:

"

)

;

scanf

(

"

%[^

\

n]

"

,

line

)

;

for

(

i

=

0

;

line

[

i

]

!='\

0

'; ++

i

)

{

if

(

line

[

i

]

=='

a

' ||

line

[

i

]

=='

e

' ||

line

[

i

]

=='

i

' ||

line

[

i

]

=='

o

' ||

line

[

i

]

=='

u

' ||

line

[

i

]

=='

A

' ||

line

[

i

]

=='

E

' ||

line

[

i

]

=='

I

' ||

line

[

i

]

=='

O

' ||

line

[

i

]

=='

U

'

)

{

++

vowels

;

}

else

if

(

(

line

[

i

]

='

a

'&&

line

[

i

]

<='

z

'

)

||

(

line

[

i

]

='

A

'&&

line

[

i

]

<='

Z

'

)

)

{

++

consonants

;

}

else

if

(

line

[

i

]

='

0

' &&

line

[

i

]

<='

9

'

)

{

++

digits

;

}

else

if

(

line

[

i

]

==' '

)

{

++

spaces

;

}

}

printf

(

"

Vowels: %d

"

,

vowels

)

;

printf

(

"

\

nConsonants: %d

"

,

consonants

)

;

printf

(

"

\

nDigits: %d

"

,

digits

)

;

printf

(

"

\

nWhitespace: %d

"

,

spaces

)

;

return

0

;

}

The output is:



输入一个字符串: runoob123 erkcomsww dfrunoob

元音: 8

辅音: 15

数字: 3

空白符: 2

C Language Examples C Language Examples