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

C Exercise 17

C Exercise 17

100 Classic C Language Examples 100 Classic C Language Examples

**Problem:** Enter a line of characters and count the English letters, spaces, digits, and other characters separately.

**Analysis:** Use a while statement with the condition that the input character is not '\n'.

Example

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

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

#include

<

stdio.h

int

main

(

)

{

char

c

;

int

letterCount

=

0

,

spaceCount

=

0

,

digitCount

=

0

,

otherCount

=

0

;

printf

(

"

Please enter some characters:

\

n

"

)

;

while

(

(

c

=

getchar

(

)

)

!= '\

n

'

)

{

if

(

(

c

= '

a

' &&

c

<= '

z

'

)

||

(

c

= '

A

' &&

c

<= '

Z

'

)

)

{

letterCount

++;

}

else

if

(

c

= '

0

' &&

c

<= '

9

'

)

{

digitCount

++;

}

else

if

(

c

== ' '

)

{

spaceCount

++;

}

else

{

otherCount

++;

}

}

printf

(

"

Letters = %d, digits = %d, spaces = %d, others = %d

\

n

"

,

letterCount

,

digitCount

,

spaceCount

,

otherCount

)

;

return

0

;

}

The output of the above example is:



Please enter some letters:

www.runoob.com 123

字母=12,数字=3,空格=1,其他=2

100 Classic C Language Examples 100 Classic C Language Examples