C/C++实践笔记 026字符串实践
1.字符串概念
C语言没有专门的“字符串”类型,用字符数组表示
strlen求字符串长度
按%s来整体显示必须要有'\0'
单个显示不需要'\0'
char str[5]={'a','b','c','d'};
指针循环输出字符串的办法,可以改变指针的位置输出不同的字符
2.字符串初始化
二维数组,每一个元素是一个一维数组,一维数组存储了字符串,字符串可以修改
指针数组,每一个元素都是一个指针,存储了代码区的字符串常量地址,不可以修改
3.字符串的两种风格区别
数组名是一个常量,不可以赋值
根据指针初始化字符串必须先开辟空间,指向代码区不可以,不初始化也不可以
4.qsort
#include<stdio.h> #include<stdlib.h> #include<time.h> void fill(int *a,int n) { time_t ts; unsigned int num = time(&ts); srand(num); for (int i = 0; i < n; i++) { a[i] = rand() % n; } } void print(int *a, int n) { for (int i = 0; i < n; i++) { printf("\n%d", a[i]); } } int com(const void *p1, const void *p2) { const int *pint1 = p1; const int *pint2 = p2; if (*pint1 == *pint2) { return 0; } else if (*pint1 > *pint2) { return 1; } else { return -1; } } void main() { int a[100]; fill(a, 100); print(a, 100); qsort(a,100,sizeof(int),com); print(a, 100); system("pause"); }
5.字符串常见函数:strlen strcpy strstr
strlen求长度函数
strcpy字符串拷贝函数,字符串拷贝不能直接赋值,要用到这个函数
strstr字符串检索在另一个字符串是否存在

浙公网安备 33010602011771号