字符指针与字符串
-
C语言通过使用字符数组来处理字符串
-
char数据类型的指针变量称为字符指针变量
-
字符指针变量与字符数组有着密切关系,它也被用来处理字符串
-
初始化字符指针是把内存中字符串的首地址赋予指针,并不是把该字符串复制到指针中
char str[] = "Hello World";char *p = str;
-
对于一个字符串,进行大小写字母转换:
#include <stdio.h>int main() {char s[100] = {"How are you!"};char *p;p = s;while (*p != '\0') {if (*p >= 'A' && *p <= 'Z') {*p += 32;} else if (*p >= 'a' && *p <= 'z') {*p -= 32;}p++;}printf("%s\n",s);return 0;
}
- 当一个字符指针指向一个字符串常量时,不能修改指针指向的对象的值
char * p = "Hello World";*p ='h';// 错误, 字符串常量不能修改- 数组和指针绝不等价
- char s[] ="hello"和char *s ="hello"有什么区别
- 访问类似,但本质完全不同
- 不利用任何字符串函数,编程实现字符串连接的功能:
#include <stdio.h>int main() {char dest[100] = {"abc"};char *src = "def";char *p = dest;char *q = src;while (*p != '\0') {p++;}while (*q != '\0') {*p = *q;p++;q++;}*p = '\0';printf("dest:%s\n", dest); //"abcdef"printf("src:%s\n", src);return 0;
}
