本篇摘要:
1:章节导入
2:字符串和字符
---------------------------------------------------------------------------------------------------------------------------------
分析两者的区别:
# include <stdio.h>
# include <string.h>
# define DENSITY 62.4
int main()
{
float weight, volume;
int size, letters;
char name[40];
printf("Hi what's your first name?\n");
scanf_s("%s", name);
printf("%s,What's weight in pounds\n", name);
scanf_s("%f",&weight);
size = sizeof(name);
letters = strlen(name);
volume = weight/ DENSITY;
printf("Well ,%s,your volume is %2.2f cubic feet.\n",name ,volume);
printf("Also,your first name has %d letters ,\n", letters);
printf("and we have %d bytes to store it .\n", size);
return 0;
}
#include <stdio.h>
#include <string.h>
#define DENSITY 62.4
int main(void) {
float weight, volume;
int size, letters;
char name[40];
printf("Hi, what's your first name?\n");
scanf_s("%s", name, sizeof(name)); // 增加了缓冲区大小参数
printf("%s, what's your weight in pounds?\n", name);
scanf_s("%f", &weight);
size = sizeof(name);
letters = strlen(name);
volume = weight / DENSITY;
printf("Well, %s, your volume is %2.2f cubic feet.\n", name, volume);
printf("Also, your first name has %d letters,\n", letters);
printf("and we have %d bytes to store it.\n", size);
return 0;
}
如果使用 scanf_s 函数,则还需要提供字符串缓冲区的大小:
此处两个%s,因为程序要打印两次,一个存储在name中,一个由PRAISE来存储。
字符串和字符:
字符和字符串的主要区别
-
存储方式:
- 字符:占用一个字节(
char
类型)。 - 字符串:占用多个字节,是字符数组,以空字符
\0
结尾。
- 字符:占用一个字节(
-
表示方式:
- 字符:用单引号,例如
'A'
。 - 字符串:用双引号,例如
"Hello"
。
- 字符:用单引号,例如
-
操作方式:
- 字符:可以直接进行比较、赋值等简单操作。
- 字符串:通常需要使用库函数进行操作,如
strlen
、strcpy
、strcmp
等。
常见字符串操作函数
-
strlen
:计算字符串长度,不包括末尾的空字符。 -
#include <stdio.h> #include <string.h> int main() { char str[] = "Hello, World!"; int length = strlen(str); printf("Length of string: %d\n", length); return 0; }
strcpy
:复制字符串。 -
#include <stdio.h> #include <string.h> int main() { char src[] = "Hello, World!"; char dest[50]; strcpy(dest, src); printf("Copied string: %s\n", dest); return 0; }
strcat
:连接两个字符串。 -
#include <stdio.h> #include <string.h> int main() { char str1[50] = "Hello, "; char str2[] = "World!"; strcat(str1, str2); printf("Concatenated string: %s\n", str1); return 0; }