Welcome to collectivesolver - Programming & Software Q&A. A website you can trust. All programs tested and works. Contact: aviboots(AT)netvision.net.il
Bonsai Boy of New York Bonsai Trees and Accessories

BlueHost Web Hosting

Liquid Web iThemes WordPress Hosting

Ecommerce Software - Best Ecommerce Platform Made for You - Free Trial

DreamHost Web Hosting


getResponse autofunnels

Liquid Web Cloud VPS Hosting

11,619 questions

15,845 answers

573 users

How to implement substring function in C

3 Answers

0 votes
#include <stdio.h>
#include <string.h>
 
int substring(char *s, int start, int total_characters, char *sub) {
    int len = strlen(s);
     
    if (start > len) {
        printf("Start index > len");
        return 0;
    }
     
    if ((start + total_characters) > len) {
        total_characters = (len - start);
    }
     
    int i;
    for (i = 0; i < total_characters; i++) {
        sub[i] = s[start + i];
    }
    sub[i] = '\0'; 
     
    return 1;    
}
 
int main()
{
    char s[64] = "c c++ java php python", sub[64];
    int start = 2, total_characters = 3;
     
    if (substring(s, start, total_characters, sub)) {
        printf("Substring = %s\n", sub);
    }
     
    return 0;
}
 
/*

run:

Substring = c++

*/

 




answered Jul 18, 2018 by avibootz
0 votes
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char *get_substring(char *s, int start, int len) {
	char *sub = (char *)malloc((len * sizeof(char)) + 1);
	sub[len] = '\0';
	strncpy(sub, s + start, len); 
	
	return sub;
}

int main() {
	char s[64] = "c c++ java php python";
				
	char *sub = get_substring(s, 2, 4);
	puts(sub);
	free(sub);
	
	sub = get_substring(s, 6, 4);
	puts(sub);
	free(sub);

    return 0;
}

 
 
/*
run:
 
c++
java

*/

 




answered Oct 21 by avibootz
0 votes
#include <stdio.h>
#include <string.h>
  
int substring(char *s, int start, int total_characters, char *sub) {
    int len = strlen(s);
      
    if (start > len) {
        printf("Start index > len");
        return 0;
    }
      
    if ((start + total_characters) > len) {
        total_characters = (len - start);
    }

	strncpy(sub, s + start, total_characters); 
    sub[total_characters] = '\0';     
      
    return 1;    
}
  
int main()
{
    char s[64] = "c c++ java php python", sub[64];
    int start = 2, total_characters = 4;
      
    if (substring(s, start, total_characters, sub)) {
        printf("%s\n", sub);
    }
    
	start = 6; total_characters = 4;
	if (substring(s, start, total_characters, sub)) {
        printf("%s\n", sub);
    }
      
    return 0;
}

  
/*
 
run:
 
c++
java

*/

 




answered Oct 21 by avibootz
...