Abstract
How do you print a string with only one digit and one dollar?
Introduction
My classmates want to send strings to the hardware, but the APIS provided by the hardware can only send one character at a time. Here we model this situation, A single-character printed string.
C. Yan
1 # Include < Stdio. h >
2 # Include < String . H >
3
4 Void Func ( Char * S ){
5 Int I;
6
7 For (I = 0 ; I < Strlen (s); I ++ )
8 Putchar (s [I]);
9 }
10
11 Int Main (){
12 Char S [] = " Hello " ;
13 Func (s );
14 }
The above program is correct for printing hello. At first glance, it is reasonable. If you think about C in other languages, it is easy to compile the above program.
The problem lies in strlen ().
The possible implementations of the C programming language 2nd p.39, strlen () are as follows:
Int Strlen ( Char S []) {
Int I;
I = 0 ;
While(S [I]! = '\ 0')
++I;
ReturnI;
}
Or, for example, p.99's
Int Strlen ( Char * S ){
Int N;
For (N = 0 ; * S ! = ' \ 0 ' ; S ++ )
N ++ ;
ReturnN;
}
That is to say, in order to get the length of the string, we have already run an extra lap. But in fact, this lap is many characters. If it is changed to the following method, you do not have to run this cycle.
C statement/cstring_putchar.c
1 /*
2 (C) oomusou 2008 Http://oomusou.cnblogs.com
3
4 Filename: cstring_putchar.c
5 Compiler: Visual C + + 8.0
6 Description: Demo how to putchar without strlen ()
7 Release: 04/16/2008 1.0
8 */
9 # Include < Stdio. h >
10 # Include < String . H >
11
12 Void Func ( Char * S ){
13 While ( * S)
14 Putchar ( * S ++ );
15 }
16
17 Int Main (){
18 Char S [] = " Hello " ;
19 Func (s );
20 }
The C string has a very useful feature: the end of the end is '\ 0', so you only need to add 1 to the pointer until the end is' \ 0, in this way, you do not need to call strlen.
Conclusion
A very small place, once again found the clever C-language string design mechanism.
See also
(Original) An interesting question about the C-language string (c)
Reference
K & R, the C programming language 2nd, Prentice Hall