Jay Nguyen
Jay Nguyen

Reputation: 341

C - copy the last characters from an unknown length string

In C programming, suppose that I have some input strings with unknown length like:

abcde.xxx abc.xxx abcdefgh.xxx ....

How can I take the last 4 characters from them? I tried this way but it doesn't work:

char dest[] = "abcdef.ghi";
char s[5];
memset(s, '\n', sizeof s);
strncpy(s, dest - 5, 4);

But I can't use strstr() since the dest may be wrong with the format xxxx.xxx like abcd.xxxy

Upvotes: 0

Views: 976

Answers (2)

KimKulling
KimKulling

Reputation: 2833

When the string is null-terminated you can use strlen to get the lenght of the string:

char s[5];
size_t len, offset;
char dest[] = "abcdef.ghi";

len = strlen(dest);
memset( s, '\0', sizeof(char)*5);
offset = len-4;
strncpy( s, &dest[offset], 4 );

If this is not the case you can loop over the string as an array and look for your dot.

Afterwards you can use this index to calculate your correct offset. But be careful for that solution. If one string does not hate a dt and last free character you can cause an access violation.

Upvotes: 1

Devolus
Devolus

Reputation: 22074

char s[5] = {0};
size_t len = 0;
char dest[] = "abcdef.ghi";
char *p = strchr(dest, '.');

if(!p)
{
   // error no '.'
   return;
}

len = strlen(p);
if(len != sizeof(s)-1)
{
    // More or less than 3 characters plus '.'
    return;
}

strcpy(s, p);

Upvotes: 3

Related Questions