023day(指针与字符串)

172210704111-陈国佳总结《2017年11月2日》【连续023天】

标题:指针与字符串;

内容:A.观看MOOC9.2,9.3;

         B.(a).字符串常量的类型就是 char *;字符数组名类型也是char *;

char * p="Please input your name:\n";
cout << p;  //printf(p)
char name[20];
char *pName =name;
cin>>pName;
cout<<"Your name is"<<pName;

023day(指针与字符串)

字符串库函数:

023day(指针与字符串)023day(指针与字符串)023day(指针与字符串)

char szValue[20];

itoa(27,szValue,10);  //使得szValue的内容为”27“

iota(27,szValue,16);  //使得szValue的内容为”1b"

举例:

        char s1[100]="12345";
char s2[100]="abcdefg";
char s3[100]="ABCDE";
strncat(s1,s2,3); //s1="1234abc"
cout<<"1)"<<s1<<endl;
strncpy(s1,s3,3);  //s3的前三个字符拷贝到是s1,s1="ABC45abc”,当拷贝数小于被拷贝数组长度,不拷贝“/0” 
cout<<"2)"<<s1<<endl;
strncpy(s2,s3,6);        //s2="ABCDE",s3的“/0”拷贝到了s2 
cout<<"3)"<<s2<<endl;
cout<<"4)"<<strncmp(s1,s3,3)<<endl; //比较S1和s3的前三个字符,比较结果相同 
char*p=strchr(s1,'B');  //在s1中查找'B'第一次出现的位置 
if(p)  //找不到B就是NULL 
      cout<<"5)"<<p-s1<<","<<*p<<endl;  //p-s1是p到s1字符数,即'B'在s1的位置; 
else
        cout<<"5) Not Found"<<endl;
p =strstr(s1,"45a");
if(p)
   cout<<"6)"<<p-s1<<","<<p<<endl;  //输出p是从p的位置输出字符,到‘/0’结束
else
   cout<<"6)Not Found"<<endl;
cout<<"strtok usage demo:"<<endl;
char str[]="-This,a sample string,ok.";
p =strtok (str," ,.-");  //(注意,字符串里的第一个字符是空格) 
while(p !=NULL)  //p不为NULL,说明找到了一个子串 
{
cout<<p<<endl;
p =strtok(NULL," ,.-");  //后续调用,第一个参数必须是NULL 

}   

023day(指针与字符串)

明日计划:学习void指针和内存操作函数;