1字符串基本操作
//1 C语言的字符串 以零结尾的字符串
//2 在C语言中没有字符串类型 通过字符数组 来模拟字符串
//3 字符串的内存分配 堆上 栈上 全局区 (很重要)
字符数组初始化方法
数组初始化有2种方法 :默认元素个数、指定元素个数.
char buf1[] = {'a', 'b', 'c', 'd', 'e'}; //若没有指定长度,默认不分配零
//若指定长度,不够报错;buf长度多于初始化个数,会自动补充零
char buf2[6] = {'a', 'b', 'c', 'd', 'e'};
在C语言中使用字符数组来模拟字符串
C语言中的字符串是以’\0’结束的字符数组
//1 用字符串来初始化数组
char buf2[] = {‘a’, ‘b’,’c’,’d’,’\0’};
//2 字符串常量初始化一个字符数组
char buf3[] = {“abcde”}; //结论:会补充零
//strlen()求字符串的长度,注意字符串的长度不包含\0
//sizeof(类型)字符串类型,的大小,包括\0;
字符串做函数参数
不要轻易改变形参的值, 要引入一个辅助的指针变量. 把形参给接过来。
int copy_str26_good(char *from , char *to)
{
//*(0) = 'a';
char *tmpfrom = from;
char *tmpto = to;
if ( from == NULL || to == NULL)
{
return -1;
}
while ( *tmpto++ = *tmpfrom++ ) ; //空语句
printf("from:%s \n", from);
}
库函数api
快速的上手api是一种能力!
1 strcspn
int length;
//在字符str1中查找,与str2中任意字符有公共交集的位置
length = strcspn(string1, string2);
printf("Character where strings intersect is at position %d\n", length);
2 strcpy
3 strnset
将一个字符串中的前n个字符都设为指定字符ch的函数。
4 strpbrk
在源字符串(s1)中找出最先含有搜索字符串(s2)中任一字符的位置并返回,若找不到则返回空指针
char *string1 = "abcdefghijklmnopqrstuvwxyz";
char *string2 = "onm";
char *ptr;
ptr = strpbrk(string1, string2);
if (ptr)
printf("strpbrk found first character: %c\n", *ptr);
else
printf("strpbrk didn't find character in set\n");
5 strtok
分解字符串为一组字符串。s为要分解的字符,delim为分隔符字符(如果传入字符串,则传入的字符串中每个字符均为分割符)。首次调用时,s指向要分解的字符串,之后再次调用要把s设成NULL。
char input[16] = "abc,d";
char *p;
/* strtok places a NULL terminator
in front of the token, if found */
p = strtok(input, ",");
if (p) printf("%s\n", p);
/* A second call to strtok using a NULL
as the first parameter returns a pointer
to the character following the token */
p = strtok(NULL, ",");
if (p) printf("%s\n", p);
项目开发字符串模型
//char *p = “abcd111122abcd3333322abcd3333322qqq”;
//求字符串p中 abcd出现的次数
//1请自定义函数接口,完成上述需求 // i++ ++ ++
//2 自定义的业务函数 和 main函数必须分开
int getcount(char *str,char *substr,int * ncnt)
{
int ret =0;
int *tmpstr = str;
int cnt =0;
if(str == NULL || substr== NULL || len ==NULL)
{
ret =-1;
return ret;
}
while(tmpstr != NULL)
{
tmpstr=strstr(tmpstr,substr);
if(tmpstr != NULL)
{
cnt++;
tmpstr = tmpstr +strlen(substr);
}
}
*ncnt = cnt;
return ret ;
}
int main()
{
int ret = 0;
char *p = "abcd111122abcd3333322abcd3333322qqq";
int count = 0;
char sub[] = "abcd";
ret = getCount(p,sub, &count);
if (ret != 0)
{
printf("func getCount() err:%d \n", ret);
return ret;
}
ret = getCount(p,NULL, &count);
if (ret != 0)
{
printf("func getCount() err:%d \n", ret);
return ret;
}
printf("count:%d \n", count);
system("pause");
}
两头堵模型
int trimSpace(char *inbuf, char **outbuf)
{
int ret = 0;
char * p = inbuf;
int len = strlen(inbuf) -1 ;
int left =0, right = len;
char *tmp = NULL;
if (!inbuf)
{
ret = -1;
printf("inbuf is NULL. \n");
return -1;
}
while (p[left] == ' ')
left++;
while (p[right] == ' ')
right--;
if (left >= right)
{
*outbuf = NULL;
return ret;
}
*outbuf = (char*)malloc(right - left + 1);
memset(*outbuf, 0, right - left + 1);
strncpy(*outbuf, p + left,right - left);
return ret;
}