How to get substring of a string starts at specific position to specific len in C

1 Answer

0 votes
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
 
char *substr(char *s, int start_point, int sub_len) {
    char *sub = (char *)malloc((sub_len * sizeof(char)) + 1);
	
	for (int i = start_point, j = 0; i < (start_point + sub_len); i++, j++) {
		sub[j] = s[i];
	}
    sub[sub_len] = '\0';
    
	return sub;
}
 

int main() {
    char s[] = "c c++ java python";
	
	char *sub = substr(s, 0, 5);
	puts(sub);
	free(sub);
	
	sub = substr(s, strlen(s) - 6, 6);
	puts(sub);
	free(sub);
        
    return 0;
}

  
/*
run:
  
c c++
python
  
*/

 



answered Nov 14, 2019 by avibootz
...