Home > Software design >  How to access the last n elements of a string in c?
How to access the last n elements of a string in c?

Time:09-24

So I was making a code and I got stuck because I was unable to figure out how to access the the last n elements of a string. I tried using the string.h library but it did not work as there is no such function that can access the last elements of a string. Could anyone help me please ?

CodePudding user response:

char *lastN(const char *str, size_t n)
{
    size_t len = strlen(str);
    return (char *)str   len - n;
}


int main(void)
{
    printf("`%s`\n", lastN("1234567890", 4));
}

CodePudding user response:

The header <string.h> contains function strlen that returns the length of a passed string. The function is declared like

    size_t strlen(const char *s);

Strictly speaking the last character of a string is its terminating zero character '\0'. But it seems by the last n characters of a string you mean n characters before the terminating zero.

To be able to get a pointer to the last n characters of a string the string should have at least n characters.

You could write a function the following way. If the passed string contains less than n characters then the function returns a pointer to the string itself.

char * last_n( const char *s, size_t n )
{
    size_t length = strlen( s );

    return ( char * )( length < n ? s : s   length - n );
} 

Here is a demonstrative program.

#include <stdio.h>
#include <string.h>
#include <ctype.h>

char * last_n( const char *s, size_t n )
{
    size_t length = strlen( s );

    return ( char * )( length < n ? s : s   length - n );
} 

int main(void) 
{
    char s[] = "Hello world!";
    
    char *p = last_n( s, 6 );
    
    puts( p );
    
    for ( char *current = p; *current != '\0';   current )
    {
        *current = toupper( ( unsigned char )*current );
        putchar( *current );
    }
    putchar( '\n' );
    
    return 0;
}

The program output is

world!
WORLD!

If you need to obtain the index where the last n characters of a string start you can write for example

char *p = last_n( s, n );
size_t pos = p - s;

Or just

size_t pos = last_n( s, n ) - s;

CodePudding user response:

In C, strings are just char arrays. And arrays are 0-indexed. This means that the first element has an index of 0, the second element has an index of 1, ..., and the last element has an index of n-1, assuming n is the length of the string (or the char array).

char *string = "Hello";
int len = strlen(string);
printf("%c", string[len-1]); // prints the last character 'o'

To access the last n elements, you can calculate the index from which the last sequence of n characters start: i = len - n:

// Returns the index of the first element of the last n elements
int last_n(char *string, int n)
{
    return strlen(string) - n;
}
  • Related