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

C Exercise 70

C Exercise 70

100 Classic C Language Examples 100 Classic C Language Examples

**Problem:** Write a function to find the length of a string; input the string in the main function and output its length.

**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

int

length

(

char

s

)

;

int

main

(

)

{

char

str

[

100

]

;

// The array length can be increased as needed

printf

(

"

Please enter a string:

\

n

"

)

;

scanf

(

"

%s

"

,

str

)

;

int

len

=

length

(

str

)

;

// Call the length function to calculate the string length

printf

(

"

The string has %d characters.

\

n

"

,

len

)

;

return

EXIT_SUCCESS

;

}

// Find the string length

int

length

(

char

s

)

{

int

i

=

0

;

while

(

s

!= '\

0

'

)

{

i

++;

s

++;

}

return

i

;

}

The output of the above program is:



Please enter a string:

www.runoob.com

字符串有 14 个字符。

100 Classic C Language Examples 100 Classic C Language Examples