字符串指存储在内存的连续字节中的一系列字符。
C++中的字符串分为两种形式:
C-风格字符串的头文件为#include,默认以’\0’结束,存储空间有’\0’。
字符串定义形式:
char a[5] = {'h','e','l','l','o'};
char a[5] = {'a','b','c','d','\0'};
也有另外一种字符串定义:
char a[8] = "abcdefg";
char a[] = "awdda;wdaa";
字符数组或字符串的长度测量函数为sizeof、strlen
举个栗子:
定义一些字符串,求长度并运算、输出
#include
#include
using namespace std;
int main(){
char s1[100];
char s2[20] = "hello!";
char s3[] = "a";
char s4 = 'a';
char s5[3] = {'a','b','c'};
char s6[3] = {'a','b','\0'};
cin >> s1;
cout << strlen(s1) << endl;
cout << s1 << " " << s2 << " " << s3 << " " << s4 << " " << endl;
cout << s5 << " " << s6 << " " << endl;
cout << "djawdawda" "123" << endl;
cout << "dwaddadadw"
"123" << endl;
cout << "adawdada 123" << endl;
return 0;
}
运行结果

【C 风格字符串的输入方式有cin、getline和get】
使用cin和get后会将换行符保留在输入序列中,解决办法为再调一次cin.get。



C++ string类字符串的长度没有限制,其头文件为#include。C++中的string类隐藏了字符串的数组性质,使用户可以像处理普通变量一样处理字符串。
注意
字符串的长度测量函数有.length()和.size()

C++ string类字符串的输入方式有cin和getline
来个栗子:
输入3个字符串,找出其中最小的字符串
#include
#include
using namespace std;
string minstr(string s1 , string s2){
if(s1 < s2){
return s1;
}
else{
return s2;
}
}
int main(){
string s1 , s2 , s3 , min;
cin >> s1 >> s2 >> s3;
min = minstr(s1,minstr(s2,s3));
cout << min << endl;
return 0;
}
