如何提取除初始两个字符以外的所有字符的子字符串?

Nik*_*ava 0 c string

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

}
Run Code Online (Sandbox Code Playgroud)

438*_*427 5

问题是你的数组太小了。他们没有空间用于 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];
}
Run Code Online (Sandbox Code Playgroud)

或者

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
Run Code Online (Sandbox Code Playgroud)

由于硬编码数组大小,上述两个示例都有些不安全。这是一个更好的选择:

#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);
Run Code Online (Sandbox Code Playgroud)

  • 你应该提到第一个片段仍然很差,特别是因为硬编码的“7”。 (4认同)