首页 > 解决方案 > 如何提取除初始两个字符外的所有子字符串?

问题描述

我想提取一个子字符串,它具有除前两个之外的主字符串的所有字符。就像某个字符串有“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 );

}

标签: cstring

解决方案


问题是你的数组太小了。它们没有空间用于 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);

推荐阅读