C字符串函数(二)
C字符串函数(二)
strcpy()
作用:
拷贝整个字符串
示例代码:
拷贝以q
开头的单词
截取字符串函数:
char * s_gets(char * st, int n)
{
char * ret_val;
int i = 0;
ret_val = fgets(st, n, stdin); // 标准输入
if (ret_val)
{
while (st[i] != '\n' && st[i] !='\0')
i++;
if (st[i] == '\n')
st[i] = '\0'; // 空字符串替换换行符 -> 读到第一个换行符的时候就使用空字符串替换 -> 第一个换行符之前的内容就作为字符串的输出
else
while (getchar() != '\n')
continue; // 没读取到换行符就一直读取
}
return ret_val;
}
逻辑实现代码:
# include<stdio.h> // 标准输入输出宏
# include<string.h>
# define SIZE 40
# define LIM 5
char * s_gets(char * st, int n);
int main(void)
{
char qwords[LIM][SIZE];
char temp[SIZE];
int i = 0;
printf("Enter %d words beginning with q: \n", LIM);
while (i < LIM && s_gets(temp, SIZE))
{
if (temp[0] != 'q')
printf("%s doesn't begin with q? \n", temp);
else
{
strcpy(qwords[i], temp);
i++;
}
}
puts("Here are the words accepted:");
/** 输出拷贝字符串 */
for ( i = 0; i < LIM; i++)
puts(qwords[i]);
getchar();
return 0;
}
参数:
strcpy(目标数组, 源字符串);
关键点:
-
strcpy()
接受两个参数 -
第一个参数应为指针,且指向一块数据对象
-
第二个可以为指针、数组名、字符串常量 -> 且该指针不必指向数组开始的地方
-
声明数组分配一块存储数据的内存空间、声明指针则分配存储一个地址的内存空间
-
函数返回值类型为
char *
指针类型
不传入字符串开始的指针示例代码:
# include<stdio.h>
# include<string.h>
# define WORDS "beast"
# define SIZE 40
int main(void)
{
const char * orig = WORDS; // 因为WORDS是一个字符串,这个赋值是把头指针赋值给了orig
char copy[SIZE] = "Be the best that you can be.";
char * ps;
puts(orig);
puts(copy);
ps = strcpy(copy + 7, orig); // 复制orig从copy数组的第七位开始,返回的是一个指针,所以第二步骤进行了指针赋值的操作
puts(copy); // 输出的是修改以后的copy数组
puts(ps); // 输出的是strcpy返回的指针,注意ps是orig
if (*ps == *orig)
puts(ps);
else
printf("false!");
getchar();
return 0;
}
strncpy()
作用:
拷贝字符串,可以设置可拷贝最大字符数
示例代码:
# include<stdio.h>
# include<string.h>
# define SIZE 40
# define TARGSIZE 7
# define LIM 5
char * s_gets(char * st, int n);
int main(void)
{
char qwords[LIM][TARGSIZE];
char temp[SIZE];
int i = 0;
printf("Enter %d words beginning with q:\n", LIM);
while (i < LIM && s_gets(temp, SIZE))
{
if (temp[0] != 'q')
printf("%s doesn't begin with q? \n", temp);
else
strncpy(qwords[i], temp, TARGSIZE - 1);
qwords[i][TARGSIZE - 1] = '\0'; // 最后一位空字符 -> 字符串
i++;
}
puts("Here are the words accepted:");
for ( i = 0; i < LIM; i++)
puts(qwords[i]);
getchar();
return 0;
}
char * s_gets(char * st, int n)
{
char * ret_val;
int i = 0;
ret_val = fgets(st, n, stdin); // 标准输入
if (ret_val)
{
while (st[i] != '\n' && st[i] != '\0')
i++;
if (st[i] == '\n')
st[i] = '\0';
else
while (getchar() != '\n')
continue;
}
return ret_val;
}
注意:
- 如果源中的字符数
<n
,那么拷贝整个数组,包括空字符 - 这样就会造成目标数组不是字符串的情况 -> 空字符后还有空间 -> 这个时候应该把
n
设置成TARGSIZE - 1
-> 确保目标数组最后一位是空字符
It's a lonely road!!!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)