c - 如何提取除初始两个字符外的所有子字符串?
问题描述
我想提取一个子字符串,它具有除前两个之外的主字符串的所有字符。就像某个字符串有“0b1011”一样,我只需要“1011”。在给定的代码中,我需要字符串 c 只有“cdef”,而它包含“cdefabcdef”。
#include <stdio.h>
#include<string.h>
void main()
{
char a[6]="abcdef";
char c[4];
for(int i=2;i<6;i++)
c[i-2]=a[i];
printf("I need c: cdef\n");
printf("I get c:%s",c);
int k=strlen(c);
printf("\nlength of c: %d\n",k );
}
解决方案
问题是你的数组太小了。它们没有空间用于 C 中所需的 NUL 终止
尝试:
char a[7]="abcdef"; // Requires 6 characters and the NUL termination, i.e. 7
char c[5];
for(int i=2;i<7;i++)
{
c[i-2]=a[i];
}
或者
char a[7]="abcdef"; // Requires 6 characters and the NUL termination
char c[5];
strcpy(c, a+2); // Adding 2 to a will skip the first two characters
由于硬编码的数组大小,上述两个示例都有点不安全。这是一个更好的选择:
#define CHARS_TO_SKIP 2
char a[]="abcdef"; // a will automatically get the correct size, i.e. 7
char c[sizeof a - CHARS_TO_SKIP]; // c will automatically be CHARS_TO_SKIP smaller than a
strcpy(c, a + CHARS_TO_SKIP);
推荐阅读
- css - 无法使用 antd 显示所有相同大小的卡片并做出反应
- python - Python 中的 Azure Function App 计时器触发器不起作用
- flutter - 如何通过 Flutter 中的推送通知显示 SOS 警报和警报?
- python - 如何将两个相互匹配的列表输出到txt文件中
- linux - bash 脚本中的 Sql (postgres)
- karate - 如何在有条件的情况下调用带有标题的其他功能
- amazon-web-services - Terraform 创建用户池域时出错
- android - 如何显示具有固定高度的 TextField 的值
- html - 如何使用属性 value="true" 设置复选框的样式?
- angular - Mat-form-field 必须包含 MatFormFieldControl 错误,使用 *ngIf