Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,885 questions

51,811 answers

573 users

How to get the last N characters of a string in C

2 Answers

0 votes
#include <stdio.h>
#include <string.h>
 
#define N 2
     
int main(int argc, char **argv) 
{ 
    char s[20] = "source.c";
    int len = strlen(s);
    
    const char *last_N = &s[len - N];
     
    puts(last_N);
      
    return 0;
}
     


/*
    
run:
     
.c
  
*/

 



answered Jan 21, 2019 by avibootz
edited Apr 17, 2024 by avibootz
0 votes
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

char *get_last_N_characters(char s[], int N) {
    char *last_N_chars = malloc(strlen(s) + 1);
    
    if (last_N_chars == NULL) {
        puts("malloc error");
        exit(1);
    }
      
    strncpy(last_N_chars, s + strlen(s) - N, N); 
    last_N_chars[N] = '\0';
    
    return last_N_chars;
}

int main(void) {
    char s[] = "java c c++ c# php python";
    int N = 12;
    
    char *p = get_last_N_characters(s, N);
    
    printf("%s", p);
      
    free(p);
}
  
  
  
  
/*
run:
  
# php python
  
*/

 



answered Apr 17, 2024 by avibootz

Related questions

1 answer 115 views
1 answer 132 views
1 answer 146 views
1 answer 125 views
1 answer 125 views
1 answer 141 views
...