发布于 ,更新于 

字符数组

警告

本文有因为初学 C++ 臆想过多导致的很多谬误,待修

字符数组

输出

1
2
3
4
5
6
7
8
9
10
11
#include <iostream>
#include <cstdio>
using namespace std;
int main(){
char str[3]="ab";
// 以下三种输出方式都是遇到换行或空格不停止,而是遇到'\0'才停止
cout << str << endl;
printf("%s\n",str);
puts(str); // 等价于上面的printf语句
return 0;
}

读入

分两种情况
1.读入一个字符串,遇到空格/回车停止
使用 cin

1
2
3
4
5
6
7
8
#include <iostream>
using namespace std;
int main(){
char str[3];
cin >> str; //输入
cout << str << endl;
return 0;
}

或使用 scanf

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <cstdio>
int main(){
char str[3];
scanf("%s",str); //输入
/*
这里注意一点,str 不能写作 &str
数组名实际上是一个指针,存储数组的第一个元素的内存地址(指向数组的第一个元素)
scanf("%s",__) 这里下划线部分应当是一个内存地址,而整型、浮点、字符等类型变量中存储的不是地址而是它对应的内容,所以需要用‘&’取出它的内存地址,如取出整型(int)变量a的内存地址就是 &a。
而数组名本身就存储着内存地址,所以不需要再用 & 取一遍内存地址
*/
printf("%s",str);
return 0;
}

2.读入一行内容,输入空格不停止

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
#include <cstring>
using namespace std;
int main(){
char str[100];
fgets(str,100,stdin); // gets() 函数在 C11 标准中因为容易溢出而被删除,取而代之的是 fgets()
/*
"str"为字符串名
“100”是读入的最大字符数(一般使用数组长度即可)
“stdin”应该是一个接口,不用管,照着写就行
*/
cout << str << endl;
return 0;
}

1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>
#include <cstdio>
#include <string>
using namespace std;
int main(){
char str[100];
string str1;
cin.getline(str,100); // 字符数组使用 cin.getline()
getline(cin,str1); // string 使用 getline()
cout << str << endl << str1 << endl;
return 0;
}

常用函数1

  • strlen(str) 求字符串长度(不包含'\0')
  • strcmp(a,b) 比较两个字符串大小(ASCII 码), a < b 返回 -1 ,a == b 返回 0, a > b 返回 1(比较方式为字典序2
  • strcpy(a,b) 将字符串 b 赋值给从 a 开始的字符数组

strlen()示例

1
2
3
4
5
6
7
8
#include <iostream> // 用于输出
#include <cstring> // 或者string.h,这是C语言的头文件
using namespace std; // 用于输出
int main(){
char s[100]="abc";
cout << strlen(s) << endl;
return 0;
}

strcmp()示例

1
2
3
4
5
6
7
8
9
#include <iostream> // 用于输出
#include <cstring> // 或者string.h,这是C语言的头文件
using namespace std; // 用于输出
int main(){
char s[100];
scanf("%s",s);
cout << strcmp(s,"abc") << endl;
return 0;
}

此处将输入的字符串与 abc 进行比较

1
2
3
4
5
6
7
8
9
10
输入
#1 bac
#2 abc
#3 aac


输出
#1 1
#2 0
#3 -1

strcpy 示例

1
2
3
4
5
6
7
8
9
#include <iostream> // 用于输出
#include <cstring> // 或者string.h,这是C语言的头文件
using namespace std; // 用于输出
int main(){
char s1[100]="abc",s2[100];
strcpy(s2,s1); // s1 复制到 s2
cout << s2 << endl;
return 0;
}

输出为abc


  1. 以下三个函数均需要把字符串中每个字符循环一遍,如果我们写循环时需要用到其中一个,会导致时间复杂度提升,需要改进。 如

    1
    for (int i = 0; i <= strlen(str); i++)

    最好改写成

    1
    for (int i =  0, len=strlen(str); i <= len; i++)
    ↩︎
  2. 字典序:从前向后比,如 2 与 10,比较数字则 10 大,按字典序比较则是 2 大(因为 2>1)↩︎