字符串查找字符串
#include<stdio.h>
char* my_strstr(char*str1,char*str2)
{
char*f=str1;\\遍历原字符串指针
char*r=str1;\\记录每次字符串首地址
char*t=str2;
while(*str1)
{
r=f;
while(*f==*t&&*f !='\0')
{
f++;
t++;
}
if(*t =='\0')
{
return r;
}
\\回滚
f=r;
t=str2;
f++;
}
return NULL;
}
int main()
{
char str1[]="helloworld";
char str2[]="llo";
char*p=my_strstr(str1,str2);
printf("%s\n",p);
return 0;
}
输出结果:lloworld
指针和字符串
#include<stdio.h>
int main()
{
char ch="helloworld";
char*p=ch;
printf("%s\n",p);
\\ printf("%s\n",ch);
printf("%c\n",*(p+1);
\\取字符串里的某个值
return0;
}
输出结果:helloworld
栈区可修改,数据区不可修改
#include<stdio.h>
int main()
{
char ch="helloworld";\\栈区字符串
char*p="helloworld";\\数据区常量字符串
ch[2]='m';
\\err p[2]='m'
\\*(p+1)='m' err
printf("%s\n",ch);
printf("%s\n",p);
return 0;
}
输出结果:hemloworld
helloworld
字符串数组
#include<stdio.h>
int main()
{
char*p={"hello","world","baole"};
\\字符串排序
for(int i=0;i<3-1;i++)\\比较次数
{
for(int j=0;j<3-1-i;j++)
{
if(p[j][0]>p[j+1][0])\\两个相邻字符串首字母比较
{
char*temp=p[j];
p[j]=p[j+1];
p[j+1]=temp
}
}
}
for(int i=0;i<3;i++)
{
printf("%s\n",p[i]);
}
return 0;
}
输出结果:
baole
hello
world