Search This Blog

C Program to get a Substring from a String from Given Index

In this post we will see a c program to get a substring from a given main string from specified index to a specified index. For example, consider given a string mainstring  which is equal to "cSourceCodes.blogsppot.com". Calling the function subString(mainstring,7,11) will return "Codes".

Arguments (parameters):
First - the original string
Second - The starting index (position) of substring (counting starts from zero)
Third - The end index of substring

Both the start index and end index are inclusive.

#include<stdio.h>
#include<string.h>

char * subString(char *MainString,int fromIndex,int toIndex)
{
int Mainlength,j;
char *subStr;
Mainlength=strlen(MainString);
if(fromIndex<0||fromIndex>=Mainlength||toIndex<fromIndex||toIndex>=Mainlength)
 {
 printf("\nError in args: subString fn");
 return(NULL);
 }
subStr=(char *)malloc(1000*sizeof(char));
for(j=0;j<=toIndex-fromIndex;j++)
 *(subStr+j)=*(MainString+fromIndex+j);

*(subStr+j)='\0';
return(subStr);
}

void main()
{
char mainstring[]="cSourceCodes.blogsppot.com";
printf("%s",subString(mainstring,7,11));
getch();

}


No comments: