概述
1、实例程序:string.c的程序:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
|
#include<stdio.h>
#define MSG "YOU MUST have many talents .tell me some."
#define LIM 5
#define LINELEN 81
int
main()
{
char
name[LINELEN];
char
talents[LINELEN];
int
i;
const
char
m1[40]=
"limit yourself to one line's worth."
;
const
char
m2[]=
"IF you can't think of your anything,fake it."
;
const
char
*m3=
"nENough about me,what's your name?"
;
const
char
*mytal[LIM]={
"adding numbers swiftly"
,
"mulityplying accurately"
,
"stashing data"
,
"flowing instructions to the letter"
,
"understanding C language"
};
//初始化一个字符串指针数组
printf
(
"hi , i'm clyde the computer."
"i have many talents.n"
);
printf
(
"let me tell you some talents.n"
);
puts
(
"what were they?"
);
for
(i=0;i<LIM;i++)
puts
(mytal[i]);
puts
(m3);
gets
(name);
printf
(
"well, %s,%sn"
,name,MSG);
printf
(
"%s n %sn"
,m1,m2);
gets
(talents);
puts
(
"let me see if i have got that list:"
);
puts
(talents);
printf
(
"thanks for the information .%s.n"
,name);
return
0;
}
|
运行结果:
从中可以看出:定义字符串的方法有:使用字符串常量、char 数组、char指针、字符串数组、
2、把字符串看做指针:
实例程序:
1
2
3
4
5
6
|
#include<stdio.h>
int
main()
{
printf
(
"%s,%p,%cn"
,
"we"
,
"are"
,*
"spare farers"
);
return
0;
}
|
%s 格式输出字符串“we”,%p格式产生一个十六进制的地址,因此如果“are”是个地址,那么%p应该输出字符串中第一个字符的地址。最后
1
|
*
"spare farers"
应该产生所指向的地址中的值,即字符串*
"spare farers"
的第一个字符。
|
3、strlen() 得到字符串的长度,缩短字符串函数
示例程序:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
#include<stdio.h>
#include<string.h>
void
fit(
char
*,unsigned
int
);
int
main(
void
)
{
char
mesg[]=
"Hold on to your heads,hackers."
;
puts
(mesg);
fit(mesg,7);
puts
(mesg);
puts
(
"let's look at some more of the string."
);
puts
(mesg+8);
return
0;
}
void
fit (
char
*string,unsigned
int
size)
{
if
(
strlen
(string)>size)
*(string+size)=
' |