字符串

来源:互联网 发布:阿里云软件市场分成 编辑:程序博客网 时间:2024/06/08 12:10

C/C++学习笔记之九

字符串是C/C++中的一个重点内容,下面就将一起讨论关于字符串的相关知识。

   1.认识字符串

     字符串的定义:由于在不引入头文件的情况下,没有字符串类型,因此,我们常用字符数组或字符指针来定义字符串。

char buff[]="Hello";//字符数组以'\0'结尾。

或者char *buff="Hello";

注:字符定义为char a='a';//为单引号。

字符串常量:const char *buff="Hello,World!";

字符串常量或变量可以通过名字来访问。下面介绍两种遍历字符串的方式:

for循环:

for(int i=0;;i++){

char ch=buff[i];

if(ch==0)break;

printf("%c",ch);

}

while循环:

int count=0;

while(buff[count]){

printf("%c",buff[count++]);

}

   2.复制

复制到0为止,注意0也要拷贝。指针只是指向,而不是复制。

while(1){

str[i]=data[i]

if(data[i]=0){

str[i]=0;//需要将0也复制过去。

break;

}

i++;

}

字符串的删除(可以通过复制字符串来操作);

int count=0; 

int i=0; 

while(str[i]){

char ch=str[i];

if(ch!=del){

copy[count]=ch;

count++;

}

i++;

}

copy[count]=0;

strcpy(str,copy);

    3.字符串的分割

注:尾部截止符:str[i]=0;

例:char str[]="hello,world";//str[5]=0;

//分隔逗号

   char *str1=str; char *str2=str+6;

下面以字符串的分割方法来展示:

int seperate(char *str,char *buff[]){

int stop=0;//停止符

int start=0;//起始符

int flag=0;

int count=0;//分成几段

for(int i=0;!stop;i++){

char ch=str[i];

if(ch==0){

stop=1;

}

if(ch==','||ch==' '||ch=='\t'||ch=='\n'||ch=='\0'){

if(flag){//前面为有效字符

str[i]=0;

flag=0;

buff[count++]=str+start;

}

}else{

if(!flag){//前面为无效字符

flag=1;

start=i;

}

}

}

return count++;

}

int main(){

char str[]="Hello,World You are\t\n  china";

char *buf[100];

int count=seperate(str,buff);

for(int i=0;i<count;i++){

printf("%s\n",buff[i]);

}

return 0;

}


1 0