1.字符串连接函数strcat
其函数原型为
strcat(char[],const char[]);
作用是:将第二个字符数组中的字符串连接到第一个字符数组的字符串后面。
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
char a[]="You are so ";
char b[]="beautiful";
cout << strcat(a,b) << endl;
return 0;
}
字符串复制函数strcpy
函数原型
strcpy(char[],const char[]);
他的作用是将第二个字符数组中的字符串复制到第一个字符数组中去,将第一个字符数组中的相应字符覆盖。
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
char a[]="You are so ";
char b[]="beautiful";
strcpy(a,b);
cout<<a<<endl;
return 0;
}
字符串比较函数strcmp
其函数原型为
strcmp(const char[],const char[]);
其作用是,对两个字符串自左向右逐个字符相比(按ASCII码值大小比较),直到出现不同的字符或者‘\0’为止
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
char a[]="You are so ";
char b[]="beautiful";
cout<<strcmp(a,b)<<endl;
return 0;
}
字符串长度函数strlen
其原型为
strlen(const char[]);
他是测试字符串长度的函数。其函数的值为字符串中实际长度,不包括‘\0’在内
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
char a[]="You are so ";
char b[]="beautiful";
cout<<strlen(a)<<endl;
return 0;
}
字符串变量
- 定义字符串变量
和其他变量一样,字符串必须先定义后使用,定义字符串变量要用类名string
string str;
string str2="hello";
注意:在使用string类定义变量时,必须在本文件的开头将C++标准库中的string头文件包含进来,即应加上
#include <string>
2.字符串变量的赋值
a.直接赋值 string str="hhhh";
b.字符串变量给字符串变量赋值 str2=str1;
他的长度也会随之发生改变
也可以对字符串变量的某一字符进行操作
string word="hello";
word[2]='a';
3.字符串变量的输入输出
cin>>str1;
cout<<str1<<endl
字符串变量的运算
1.字符串复制直接用赋值号
2.字符串连接用+号
3.字符串比较直接用关系运算符
== > < !=……..