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,879 questions

51,805 answers

573 users

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

Related questions

...