字符串是一段数据。
c语言没有字符串类型,通过字符数组模拟
c语言字符串,以字符‘\0’、数字 0 结尾
先说初始化方法
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void)
{
//不指定长度,没有0结束符,有多少个元素就有多长
char buf[] = {'a','b','c'};//不知道在哪里结束该字符串,会输出乱码
printf("buf = %s\n", buf);
//指定长度,后面没有赋值的元素,自动补0
char buf1[100] = { 'a','b','c' };
printf("buf1 = %s\n", buf1);
//所有元素赋值为0
char buf2[100] = { 0 };
//char buf3[2] = {'1','2','3'};//数组越界
char buf4[50] = { '1','a','b','0','7' };
printf("buf4 = %s\n", buf4);
char buf5[50] = { '1','a','b',0,'7' };
printf("buf5 = %s\n", buf5);
char buf6[50] = { '1','a','b','\0','7' };
printf("buf6 = %s\n", buf6);
//使用字符串初始化,常用
char buf7[] = "sdfdafaf";
//strlen:测字符串长度,不包括数字0或'\0'
//sizeof:测数组长度,包括数字0或'\0'
printf("strlen = %d,sizeof = %d\n", strlen(buf7),sizeof(buf7));
char buf8[100] = "adfadfadfasdf";
printf("strlen = %d,sizeof = %d\n", strlen(buf8), sizeof(buf8));
printf("test");
char str[] = "\0129";//转义字符 \012==\n
printf("%s\n",str);
system("pause");
return 0;
}
然后是输出,分两种:[]法和指针法
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void)
{
char buf[] = "123456789";
int i = 0;
char *p = NULL;
//[]法
for (i = 0; i < strlen(buf); i++)
{
printf("%c ", buf[i]);
}
printf("\n");
//指针法
//数组名字,数组首元素地址
p = buf;
for (i = 0; i < strlen(buf); i++)
{
printf("%c ", p[i]);
}
printf("\n");
//第二种方法
for (i = 0; i < strlen(buf); i++)
{
printf("%c ", *(p+i));
}
printf("\n");
//第三种方法
for (i = 0; i < strlen(buf); i++)
{
printf("%c ", *(buf + i));
}
printf("\n");
system("pause");
return 0;
}