adsense

Hii, welcome to my site. My name is Om prakash kartik. This blog helps you to learn programming languages concepts.

Program in C and C++ to extract a substring from a given string.

 Program in C and C++ to extract a substring from a given string.



C PROGRAM
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
 char *substring(char *str, int sIndex, int eIndex){
 	int i;
 	if(eIndex < strlen(str) && sIndex < eIndex){
	 	char *sub = malloc(sizeof(eIndex- sIndex));
	 	int j = 0;
	 	for(i = sIndex; i < eIndex; i++){
	 		sub[j++] = str[i];
		 }
		 sub[j] = '\0';
		return sub;
	}else{
	   printf("\nIndex out of range.\n");
	   return "";
	}
 }
 int main(){
 	char str[] = "Hello bro, how are you.";

 	char *sub = substring(str, 0, 6);
 	printf("Sub string  = %s", sub);
 	return 0;
 }
C++ PROGRAM
#include<iostream>
#include<stdlib.h>
#include<string.h>
 using namespace std;
 char *substring(char *str, int sIndex, int eIndex){
 	int i;
 	if(eIndex < strlen(str) && sIndex < eIndex){
	 	char *sub = (char*)malloc(sizeof(eIndex- sIndex));
	 	int j = 0;
	 	for(i = sIndex; i < eIndex; i++){
	 		sub[j++] = str[i];
		 }
		 sub[j] = '\0';
		return sub;
	}else{
	   cout<<"\nIndex out of range."<<endl;
	   return "";
	}
 }
 int main(){
 	char str[] = "C++ is an object oriented programming language.";

 	char *sub = substring(str, 10, 16);
 	cout<<"Sub string  = "<< sub;
 	return 0;
 }
Output :-










Related Programs 

Post a Comment

0 Comments