019day(字符串库函数的学习)

来源:互联网 发布:linux大作业 编辑:程序博客网 时间:2024/06/06 09:25

172210704111-陈国佳总结《2017年10月29日》【连续019天】

标题:字符串库函数的学习;

内容:A.观看MOOC7.3,7.4;

           B.(a).使用字符串库函数需要#include<cstring>;字符串函数都是以'\0'判断字符串结尾;

              形参为char [ ]类型,则实参可以是char数组或字符串常量;

1.字符串拷贝

strcpy(char dest [ ],char src [ ] );//拷贝src到dest中,到'\0'为止(包括'\0');

2.字符串比较大小

int strcmp(char s1 [ ],char s2 [ ]); //返回0,s1=s2,返回负数,s1<s2,返回正数,s1>s2;

3.求字符串长度

int strlen(char s [ ]); //到'\0'为止,不包括'\0';

4.字符串拼接

strcat(char s1[ ],char s2[ ]);//将s2拼接到s1后面(可能会发生数组越界);

5.字符串转成大小写

大写:strupr(char s[ ]);

小写:strlwr(char s[ ]);

例:#include<cstring> 
#include<cstdio>
using namespace std;
void PrintSmall( char s1[],char s2[])
{
if(strcmp(s1,s2)<=0)
    cout<<s1;
    else
         cout<<s2;
}
int main(){
char s1[30],s2[40],s3[100];
strcpy(s1,"Hello");
strcpy(s2,s1);
cout<<"1)"<<s2<<endl;
strcat(s1,",world");
cout<<"2)"<<s1<<endl;
cout<<"3)";PrintSmall("abc",s2);cout<<endl;//大写字母的ASCLL码要小于小写的 
cout<<"4)";PrintSmall("abc","aaa"); cout<<endl;
int n=strlen(s2);
cout<<"5)"<<n<<","<<strlen("abc")<<endl;
strupr(s1);
cout<<"6)"<<s1<<endl;
return 0; 

运行结果如下:


             (b).strlen的用法;

错误示例:char s[100]="test";

                   for(int i = 0;i<strlen(s);++i){s[i] =s[i]+1//此句不重要;}//该程序是为了遍历s数组

1.strlen函数的执行都需要时间,且时间和字符串长度成正比;每次循环都要调用strlen函数,浪费效率;

可改为:

int len =strlen(s);for(int i=0;i<len;++i){ }

或:for(int i=0;s[i];++i){ }//当s[i]==0,字符串终止,0判断为false;

例题:编写判断子串的函数:

int Strsre(char s1[ ],char s2[ ]);

如果s2不是s1的子串,返回-1;如果是,返回s2在s1中第一次出现的位置;空串是任何串的子串,且出现的位置是0;

如:int Strstr(char s1[],char s2[])
{
if( s2[0]==0)
   return 0;
for(int i=0;s1[i];++i){//枚举比较起点
 int k=i,j=0;
 for( ;s2[j];++j,++k){
     if(s1[k]!=s2[j])
     break;
 } 
 if(s2[j]==0)
      return i;
}
return -1;
}

使用如下:

int main()
{
char s1[5]={1,2,3,2,3};
char s2[2]={2,3};
cout<<Strstr(s1,s2);
return 0;
}运行后,结果如下:


明日计划:学习指针;




原创粉丝点击