字符串初始赋值的三种方法
1 2 3 4 5 6 7 8 9 10 11 12 13
| #include<iostream> using namespace std; int main() { char a[10] = {'a', 'b', 'c', '\0'}; char b[10] = {'a', 'b', 'c', 'd', 'e', 'f', 0, 'h', 'i', 'g'}; char c[10] = {"09AZaz"}; char d[10] = "09AZaz"; string b="aaaa"; cout<<b; return 0; }
|
字符串的三种输入方法
单个逐一输入
该方法规定字符串长度,也就是必须输入规定长度,少补(再输入)多截断,且不包含分隔符(空格,制表符,换行符,回车)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| #include<iostream> using namespace std; int main() { char a[20]; for(int i=0;i<20;i++) { cin>>a[i]; } for(int i=0;i<20;i++) { cout<<a[i]; } cout<<a; return 0; }
|
注意:这里的数组是char型的,可以整体输出,但是如果是int型的,输出a会输出数组a第一个元素的地址,并且没有输入的元素会补成0,而不是NULL
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| #include<iostream> using namespace std; int main() { int a[20]={5,6,3,0}; char b[20]={'a','b','c'}; cout<<a<<endl; cout<<b<<endl; for(int i=0;i<20;i++) { cout<<a[i]<<endl; } cout<<endl; for(int i=0;i<20;i++) { cout<<b[i]<<endl; } return 0; }
|
整体输入
从键盘输入流中提取第一个连续字符串(不包含分隔符)
1 2 3 4 5 6 7 8 9
| #include<iostream> using namespace std; int main() { char b[20]; cin>>b; cout<<b; return 0; }
|
按行输入
不限制输入字符数,也可以输入空格和制表符,遇到回车/换行符结束
1 2 3 4 5 6 7 8 9
| #include<iostream> using namespace std; int main() { string str; getline(cin,str); cout<<str<<endl; return 0; }
|
cstring的简单使用
这里的cstring和string不同
string是C++标准库头文件,包含了拟容器class std::string的声明(不过class string事实上只是basic_string char的typedef),用于字符串操作。
cstring是C标准库头文件string.h的C++标准库版本,包含了C风格字符串(NUL即’\0’结尾字符串)相关的一些类型和函数的声明,例如strcmp、strchr、strstr等。cstring和string.h的最大区别在于,其中声明的名称都是位于std命名空间中的,而不是后者的全局命名空间。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
| #include<iostream> #include<cstring> using namespace std; int main() { char s1[10] = "abc"; char s2[10] = "123"; cout << strcmp(s1, s2) << endl; cout << strcmp(s1, "abc") << endl; cout << strcmp(s1, "abd") << endl; cout << "-----" << endl; cout << "s1 = " << s1 << endl; cout << "s2 = " << s2 << endl; strcpy(s1, s2); cout << "s1 = " << s1 << endl; cout << "s2 = " << s2 << endl; strcat(s1, s2); cout << "s1 = " << s1 << endl; cout << "s2 = " << s2 << endl; cout <<strlen(s1) <<endl; return 0; }
|
这里有必要区别一下反应数组长度的几个函数:
其中str.length()和str.size()是同义词,返回同样的值。
strlen(str)是用于求字符数组的长度,其参数是char。