How to implement substring between two indexes function in C

1 Answer

0 votes
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
 
char *get_substring(char *s, int i, int j) {
    int len = j - i + 1;
    char *sub = (char *)malloc((len * sizeof(char)) + 1);
    sub[len] = '\0';
    strncpy(sub, s + i, len); 
     
    return sub;
}
 
int main() {
    char s[64] = "c c++ java php python";
                 
    char *sub = get_substring(s, 2, 6);
     
    puts(sub);
    free(sub);
     
    return 0;
}
 
  
  
/*
run:
  
c++ j
 
*/

 



answered Oct 21, 2019 by avibootz
edited Oct 22, 2019 by avibootz

Related questions

1 answer 134 views
1 answer 930 views
1 answer 107 views
1 answer 123 views
1 answer 120 views
...