您的位置:首页 > 编程语言 > C语言/C++

关于C语言字符串数组

2009-04-16 10:48 375 查看


strcat
函数
strcat函数用于连结两个字符串。一般形式是:
strcat(字符串1,字符串2);
strcat函数把字符串2连结在字符串1的后面。其中,参数“字符串1"必须是字符串变量,而"字符串2"则可以是字符串常量或变量。
调用strcat函数后,str1中字符后的'/0'取消,只在新串最后保留一个'/0'。
注意:strcat函数不检查字符串1的空白位置是否装得下字符串2。如果没有足够的空间,多余的字符将溢出至邻近的内存单元,破坏这些单元原来的内容。所以连结前应调用strlen函数进行检验,确保不发生溢出。记住在检验时给长度加1,为新字符串的结束符'/0'留一个位置。
例: strcat函数示例。
static char str1[30]={"Pelple's Republic of
"};/*注意空格*/
static char str2[]={"China"};
printf("%s",strcat(str1,str2));
输出:
Pelple's Republic of China

2.sizeof()
sizeof()是编译时常量,也就是它的值在编译时就已经确定了,因此无论是否对字符串做了strcat(),sizeof(s)的值不变。
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
//output:
//strlen=14, sizeof=15
//strlen=26, sizeof=15
//this is a test!!!!!!!!!!!!

int
main(int argc,char** argv){
// if we don't give the array lenth, sizeof(s)=strlen(s)+1=15
// static char *sp="this is a test";
static char s[]="this is a test";
// sizeof(s) is determined during compilation!!! if we change the
// string after definition, sizeof(s) will not be change.
// so it's bettern to use strlen
printf("strlen=%d, sizeof=%d/n",strlen(s),sizeof(s)); //sizeof(s)=15
strcat(s,"!!!!!!!!!!!!"); // BE CAREFUL to do this :s[] overflow!!!
// we should allocate a big enough s[100].
// but on some machine this will produce
// the expected result.
printf("strlen=%d, sizeof=%d/n",strlen(s),sizeof(s)); //sizeof(s)=15
printf(s);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: