C Language Examples - Calculate String Length
Calculate the length of a string.
Example - Using strlen()
#include
<
stdio.h
#include
<
string.h
int
main
(
)
{
char
s
[
1000
];
int
len
;
printf
(
"
Enter a string:
"
)
;
scanf
(
"
%s
"
,
s
)
;
len
=
strlen
(
s
)
;
printf
(
"
String length: %d
"
,
len
)
;
return
0
;
}
The output is:
输入字符串: runoob
字符串长度: 6
Example - Without using strlen()
#include
<
stdio.h
int
main
(
)
{
char
s
[
1000
]
,
i;
printf
(
"
Enter a string:
"
)
;
scanf
(
"
%s
"
,
s
)
;
for
(
i
=
0
;
s
[
i
]
!= '\
0
'; ++
i
)
;
printf
(
"
String length: %d
"
,
i
)
;
return
0
;
}
The output is:
输入字符串: runoob
字符串长度: 6
C Language Examples