您的位置:首页 > 其它

字符和字符串(字符数组)处理

2009-09-07 18:04 295 查看
几个常见特殊字符的整型数字

描述char

int
空格' '

32
TAB键'/t'9
回车换行LF

0x0A

10
文件结束EOF

字符串结束符号

0数字0(不是字符‘0’)

TAB字符处理要小心,经过到记事本copy/paste后,TAB键被转化成几个空格

for(;str[i]==' '||str[i]=='

';i++);

但经过到记事本copy/paste后,TAB键被转化成几个空格

所以系统总报warning:

tmp.c:58: warning: comparison is always false due to limited range
of data type

tmp.c:59:27: warning: character constant too long for its
type

‘a’与”
a”的区别(实际就是字符和字符串的区别)

‘a’

1字节‘a’
” a”

2字节

‘a’’/0’
字符串数组char str[20],至少有一个str
是0

strcpy(str,”123”);

str[0]=’1’

str[1]=’2’

str[2]=’3’

str[3]=0

字符串指针=字符串数组名=字符串数组第一个元素
的地址(&)

char *s;

char str[20];

s =
str = &str[0]

字符串数组和字符串指针的相同和不同

作为函数参数
,字符串数组名和字符串指针没区别

showtable(char s[50]);

showtable(char *s);

在printf上
,字符串数组和字符串指针没区别

char s[20];

char *p
;

p="a point";

sprintf(s,"a char arrage");

printf("p's value is : %s
/n",p
);

printf("s's value is : %s
/n",s
);

p's value is : a point

s's value is : a char arrage

字符串数组和字符串指针在赋值上不同

字符串数组无法直接赋值,只能用sprintf,strcpy,strcat
char s[20];

char *p;

char s[20];

p="a point";

sprintf(s,"a char arrage");

strcpy(s,"a char arrage");

字符串指针
只支持printf,不支持scanf,scanf还是建议用字符串数组

对指针初始赋值,不分配空间,可以支持printf

char *p;

p="ppp";

printf("p's value is : %s/n",p);

[macg@localhost mysqltmp]$ ./tt

p's value is : ppp

对指针初始赋值,不分配空间,不支持scanf

char *p;

p="ppp";

scanf("%s",p);

[macg@localhost mysqltmp]$ ./tt

Segmentation
fault

如何使字符串指针支持scanf操作,必须用malloc分配字节

#include
<stdlib.h>

main()

{

char s[20];

char *p;

int ret;

p=malloc(20);

scanf("%s",p);

printf("p's value is : %s/n",p);

free(p);

[macg@localhost mysqltmp]$ ./tt

dddd

p's value is : dddd

对malloc要求:

#include<stdlib.h>

malloc返回指针 p=malloc(20);

记着要free(指针) free(p);

虽然也可以用字符串数组初始化字符串指针,但不建议

实际就等于操作的是字符串数组了,多此一举

char s[20];

char *p;

p=s;

字符串不建议直接赋值和比较,用函数strcpy

strcpy(char*,char *)

字符串拷贝函数

后者拷贝到前者

strcat(char*,char
*)

字符串追加函数

后者追加到前者后

strcmp(char*,char
*)

对字符串是不允许做==或!=的运算

只能用字符串比较函数

字符串比较只能采用strcmp

不能用同一个字符串数组赋值给多个字符串指针,这样会造成两个字符串指向同一空间
.

char *name,*media,a[30],s[80],c;

name=media=a;

以后修改meida,name也会跟着改变

gets读字符串也有”连读”问题,
不过这个影响的不是scanf前面剩下的'/n',而是前面剩下的0

Char a[20];

gets(a)

while (a[0]==0)
gets(a);

scanf读字符串,只能读到空格,所以scanf只能读单个单词的字符串,不能读"句子"

char s[80];

scanf("%s",s);

printf("your input is :%s",s);

[macg@localhost mysqltmp]$ ./tt

abc def hig

your input is :abc

gets能克服scanf的缺陷,读字符串包含空格

char a[30];

gets(a);

printf("your input is :%s/n",a);

[macg@localhost mysqltmp]$ ./tt

abc efd sdd

your input is :abc efd sdd

fgets字符串指针改成字符串数组,消灭了Segmentation fault错误

char *re,*rec
;

re=fgets(rec,100
,srcstream);

出Segmentation fault错误

改成

char *re,rec[100];

re=fgets(rec,100,
srcstream);

错误消失

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐