您的位置:首页 > 其它

字符数组函数,连接strcat 复制函数strcpy 比较函数strcmp 长度函数 strlen

2018-01-01 00:42 621 查看
之前我们学习数据类型的时候,有一个类型 char ,这个类型允许我们在里边放一个字符

char variable1='o';

char variable2='k';

#include <iostream>
using namespace std;

int main(){
//C++当中字符数组赋值,''单引号中不能为空
char talk[10]={'I',' ','a','m',' ','h','a','p','p','y'};
for(int i=0;i<10;i++){
cout<<talk[i];
}
cout<<endl;
}


使用字符二维数组制作输出一个钻石图形。

#include <iostream>
using namespace std;

int main(){
//C++当中字符数组赋值,''单引号中不能为空
char talk[5][5]={{' ',' ','*'},
{' ','*',' ',' ','*'},
{'*',' ',' ',' ','*'},
{' ','*',' ','*'},
{' ',' ','*'}};
for(int i=0;i<5;i++){
for(int j=0;j<5;j++)
cout<<talk[i][j];
cout<<endl;
}
cout<<endl;
}


这个字符数组的长度是多少?
char talk[10]={'I',' ','a','m',' ','h','a','p','p','y'};
字符串 I am happy
string talk="I am happy";
两者意义上市一致的,但是长度上是不一致的。c++在字符y的后边自动添加了一个'\0',这个一个符号,表示字符串的结束。
string 和我们之前学的int float double boolean char 基本数据类型不同,可以直接在c++程序中使用。
string 是不能在c++中直接使用。


#include <iostream>
#include <string>
using namespace std;

int main(){
int a=1;
cout<<a;
//s的长度是多少呢? 是11 c++在字符串使用的时候自动添加了一个'\0'
//,当c++系统输出字符串的时候检测到 '\0',结束
string s="I am happy";
//arr的长度是多少呢? 是11
char arr[]="I am happy";
//arr2的长度是多少呢?是10
char arr2[]={'I',' ','a','m',' ','h','a','p','p','y','\0'};
//arr与arr2 是等价的
cout<<endl<<arr;
cout<<endl<<arr2;
cout<<endl;
cout<<s;
return 0;
}


char str[5];

cin>>str;

如果输入字符串为Beijing字符串长度超出,也不会报错,(与其他数据类型不同)但是会破坏其他空间中的数据,有可能引发问题。

 

使用字符串处理函数,进行字符串的操作

第一个,字符串连接

使用strcat(char[],const char[])

举例:

#include <iostream>
#include <string.h>
using namespace std;

int main(){
//C++当中字符数组赋值,''单引号中不能为空
char str1[30]="People's Republic of ";
char str2[]="China";
cout<<strcat(str1,str2);

}


 第二个,字符串复制

#include <iostream>
#include <string.h>
using namespace std;

int main(){
//C++当中字符数组赋值,''单引号中不能为空
char str1[30];
char str2[]="China";
strcpy(str1,str2);
cout<<str1<<"   ~    "<<str2;

}


 第三个,字符串比较

#include <iostream>
#include <string.h>
using namespace std;

int main(){
//按照字母表的顺序,在后边就大 ASCII
char str1[]="Zoa";
char str2[]="Zoble";
int x=strcmp(str1,str2);
cout<<x;

}


如果相等为0,如果大于为1,如果小于为-1;

第四个,字符串长度函数

#include <iostream>
#include <string.h>
using namespace std;

int main(){
//字符串"Zoa",实际上等价于{'Z','o','a','\0'}
//字符串长度函数 求的值是实际长度,不是真实长度
char str1[10]="Zoa";
char str2[30]="Zoble";
int x=strlen(str1);
int y=strlen(str2);
cout<<x<<"~~~"<<y;

}


 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐