字符串声明:
char str[10] = {'h','e','l','l','o','\0'};// 读写
char str1[10] = "hello";
char *str2 = "hello";// 只读
输入字符串
printf("输入一个字符串:\n");
char str[10];
->1
gets(str);
printf("str=%s", str);
->2
scanf("%s",str);
printf("str=%s", str);
->3
fgets(str, 10, stdin);
printf("str=%s", str);
字符数组赋值,计算长度
// 给字符数组赋值
char str[10] = "abc";
for (int i = 0; i < 10; ++i) {
str[i] = "12345678\09"[i];
}
printf(str);
strcpy(str,"aligadou\n");
printf(str);
printf("%lu\n", sizeof(str));
printf("%lu\n", strlen(str));
-> 自定义计算,实际不这么用
int mystrlen(char *str) {
int i = 0;
while (*(str + (++i)));
return i;
}
字符串拼接,比较
void mystrcat(char *s1,char *s2){
while(*s1) s1++;
while(*s1++ = *s2++);
}
-> 这里只能用字符数组
char s1[] = "abc";
char s2[] = "123";
mystrcat(s1,s2);
printf("%s",s1);
-> 指针分配内存方式
char * s4 = (char*)calloc(10, sizeof(char));
scanf("%s",s4);
printf(s4);
free(s4);
-> strcpy
char ms[10] = "11111\0";
strncpy(ms, "123456",3);
-> 略有不同
strcpy(ms,"2er");
printf(ms);
printf("%d\n",strcmp("abcf","abce"));
网友评论