小记:静默如初,安之若素
1. 回顾c中的字符串
- 双引号常量字符串:“hello”
- 字符指针 : char *
- 字符数组: char[ ]
1 #include <stdio.h>
2 #include <string.h>
3
4 int main(void)
5 {
6 //char *p = "hello world";
7 //strcpy(p, "jiang");//编译无错误,运行出现段错误
8 //printf("%s\n", p);
9
10 //char arr[] = "hello world";
11 //strcpy(arr, "jiangjjjjjjjjjjjj");//容易出现内存越界问题
12 //printf("%s\n", arr);
13
14 char *p = "hello";
15 char arr[] = "world";
16 p = arr;//ok
17 //printf("%s\n", p);
18 //arr = p;//error, 数组是指针常量,不可以修改
19
20 if(strcmp(p, "hello"))//strcmp相等时返回0,注意C中一些关于字符串的逻辑问题
21 {
22 printf("相等\n");
23 }
24 return 0;
25 }
2 C++中的字符串
- C++中兼容C的字符串的同时,增加了string类型专门表示字符串(string类型是结构体类型)
- 定义字符串
string s;//定义一个字符串
string s = “hello”; // 定义字符串同时初始化
//下面两种写法和上面的写法等价
string s = string("hello");
string s("hello");
- 字符串的基本操作
1). 字符串拷贝 :=
string s1 = "hello";
sting s2 = "ren";
s1 = s2; //拷贝
cout<<s1<<endl; // "ren",内存在堆区动态分配
2). 字符串连接 :+ +=
string s1 = "hello";
stirng s2 = "world";
string s3 = s1 + s2;
cout<<s3<<endl; // "hello world"
s1 += s2;
cout<<s1<<endl;//"hello world"
3). 字符串比较 : == != > < >= <=
string s1 = "hello";
if(s1 == "hello"){...}//1:逻辑真
if(s1 > "ren"){...}//字符串从首字母开始比较字母对应的ASCII码值
4). 获取字符串中某个字符:[]
string s1 = "hello";
cout<< s1[0] << endl; //'h'
s1[0] = 'H';
cout<< s1[0] << endl; // 'H'
5). string类型中常用函数
size()/length() :获取字符串的长度
c_ctr() : 将stirng 转换为C中的const char * 字符串
to_string() : 将其他类型转为string 类型
eg:
string s = "hello";
s.size(); //5
s.length(); //5
const char* p = s.c_str();
int i = 5;
string ii = to_string(i);
- 代码测试
1 #include <iostream>
2 #include <cstring>
3
4 using namespace std;
5
6 int main(int argc, char * argv[])
7 {
8 string s = "hello";
9 cout<< s <<endl; //"hello"
10
11 //拷贝
12 string s2 = s;
13 cout<< s2 << endl; // "hello"
14
15 //连接
16 s = s + "world";
17 cout<< s << endl; // "hello world"
18
19 //比较
20 cout<< (s == s2) << endl; //0
21 cout<< (s2 == "hello") << endl; // 1
22
23 //获取字符串中的某个字符
24 s[0] = 'H';
25 s[6] = 'w';
26
27 cout << s << endl; //Hello World
28
29 //获取字符串的长度
30 cout << s.size() << endl; // 10
31 cout << s.length() << endl; //10
32 cout << strlen(s.c_str()) << endl;//C中获取字符串的长度
33
34 return 0;
35
36 }
运行结果:
hello
hello
helloworld
0
1
Hellowwrld
10
10
10
- 测试 :获取一个字符串中 ‘a’ 的数量
1 #include <iostream>
2 #include <cstring>
3
4 using namespace std;
5
6 int main(int argc, char *argv[])
7 {
8 cout<<"输入字符串:"<<endl;
9 string s;
10 //cin >> s;//碰到空白符结果
getline(cin, str);//碰到换行(回车)结束
11 int num = 0;
12 for(int i = 0; i < s.size(); i++)
13 {
14 if(s[i] == 'a')
15 {
16 num++;
17 }
18 }
19 cout << "a num : "<<num<<endl;
20 return 0;
21 }
输入字符串:asdasdaasddaad
运行结果: a num : 6
输入字符串:asd asd aas ddaad
运行结果: a num : 6