参考博客:【C语言学习】——字符、字符串_c 字符和字符串-CSDN博客
1、赋值使用的两种方式:数组与指针
数组,注意第二种的坑:
char str1[] = "12345678";
char str2[6] = "hello";//因为字符数组内若没有\0就不是字符串,所以编译器会自动为末尾添加\0,这里的数字就是6
指针定义:
char *p = "1234567";
从内存分配上看,这两种存储方式是:数组在栈上,指针在堆上
二、常用的字符使用:加上头文件
#include <stdio.h>
#include <string.h>
1、strlen(计算字符长度)
#include <stdio.h>
#include <string.h>
int main()
{
const char *message = "Hello, World!";//注意空格,所以是13个
size_t length = strlen(message);
printf("Length of the string: %d\n", length);//13
//注意
return 0;
}
2、strcpy_s(C11标准,复制字符串)
#include <stdio.h>
#include <string.h>
int main()
{
char destination[20];
const char *source = "Copy me!!!";
strcpy_s(destination,11, source);
printf("Copied string: %s\n", destination);
return 0;
}
3、strncpy_s(C11标准,复制字符串,可以进行部分字符串的复制)
#include <stdio.h>
#include <string.h>
int main()
{
char destination[10];
const char *source = "Copy me!";
strncpy_s(destination,9,source, 20);
destination[5] = '\0'; // 手动添加 null 终止符
printf("Copied string: %s\n", destination);
return 0;
}
//strcpy_s()和strncpy_s()区别:strcpy_s没有拷贝字符串后的\0字符,而strcpy_s会将后面的\0也进行拷贝
4、strcat_s拼接字符串
#include <stdio.h>
#include <string.h>
int main()
{
char destination[20] = "Hello!";
const char *source = "World!";
strcat_s(destination,13, source);
destination[10] = '\0'; // 手动添加 null 终止符
printf("Concatenated string: %s\n", destination);
return 0;
}
5、strcmp比较字符串
#include <stdio.h>
#include <string.h>
int main()
{
const char *str1 = "abcdef";
const char *str2 = "abcd";
int result = strcmp(str1, str2);
printf("Comparison result: %d\n", result);//str1<str2,返回负数,相等为0,大于返回正数
return 0;
}
6、strstr查找字符串
#include <stdio.h>
#include <string.h>
int main()
{
const char *sentence = "This is a sample sentence.";
const char *word = "sample";
char *result = strstr(sentence, word);
if (result != NULL)
{
printf("Substring found: %s\n", result);//最终结果: sample sentence
}
else
{
printf("Substring not found.\n");
}
return 0;
}
7、gets() :(不推荐使用)功能是从输入缓冲区中读取一个字符串存储到字符指针变量 str 所指向的内存空间
#include <stdio.h>
#include <string.h>
int main()
{
char str[20] = "\0"; //字符数组初始化\0
printf("请输入字符串:");
gets(str);
printf("%s\n", str);
return 0;
}
8、sprintf_s的使用:格式化字符串输出到字符数组
#include <stdio.h>
#include <string.h>
int main()
{
char str[20];
char *s1 = "hello";
char *s2 = "world";
sprintf_s(str, sizeof(str), "%s %s", s1, s2);//sizeof(str)的大小必须大于等于待写入字符串的大小加一,否则会出错。
printf("%s\n", str);
return 0;
}
9、puts() - 字符串输出
#include <stdio.h>
#include <string.h>
int main()
{
char *output = "Hello, World!";
puts(output);
return 0;
}
10、fgets、fputs,字符输入输出流
#include <stdio.h>
#include <string.h>
int main()
{
char str[20]; /*定义一个最大长度为19, 末尾是'\0'的字符数组来存储字符串*/
printf("请输入一个字符串:");
fgets(str, 19, stdin); /*从输入流stdin中读取19个字符到字符数组str中*/
fputs(str, stdout); //将字符数组的内容输出到输出流stdout中
return 0;
}