C program to extract a portion of string (Substring Extracting in C)

In this program, we are taking a string from the user and extracting the substring (a portion of the string). To get the substring from the string, we are taking from and to (start and end) index.

Here, we are implementing a user defined function named getSubString(), this function will take following four arguments and return either 0 (on successful execution) or 1 (if execution failed)

Function getSubstring() arguments

char *source - Source string which will be read from the user and provided to the function as an argument
char *target - Target string, substring will be assigned in this variable
int from - Start index from where we will extract the substring (it should be greater than or equal to 0 and less than string length)
int to - End index, the last character of the substring (it should be less than string length)

C program to get substring from a string

#include <stdio.h>

/*Function declaration*/
int getSubString(char *source, char *target,int from, int to);

int main()
{
	char text [100]={0};
	char text1[50] ={0};
	int from,to;
	
	printf("Enter a string: ");
	fgets(text,100,stdin);
	
	printf("Enter from index: ");
	scanf("%d",&from);
	printf("Enter to index: ");
	scanf("%d",&to);	
	
	printf("String is: %s\n",text);
	
	if(getSubString(text,text1,from,to)==0)
	    printf("Substring is: %s\n",text1);
    else
        printf("Function execution failed!!!\n");
	
	return 0;
}

/*Function definition*/
int  getSubString(char *source, char *target,int from, int to)
{
	int length=0;
	int i=0,j=0;
	
	//get length
	while(source[i++]!='\0')
		length++;
	
	if(from<0 || from>length){
		printf("Invalid \'from\' index\n");
		return 1;
	}
	if(to>length){
		printf("Invalid \'to\' index\n");
		return 1;
	}	
	
	for(i=from,j=0;i<=to;i++,j++){
		target[j]=source[i];
	}
	
	//assign NULL at the end of string
	target[j]='\0'; 
	
	return 0;	
}

Output

First run:

Enter a string: This is IncludeHelp 
Enter from index: 5 
Enter to index: 12
String is: This is IncludeHelp
Substring is: is Inclu

Second run:
Enter a string: This is IncludeHelp 
Enter from index: 5 
Enter to index: 50
String is: This is IncludeHelp
Invalid 'to' index
Function execution failed!!!

C Strings User-defined Functions Programs »





Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.