Friday, March 31, 2017

C plus plus program to extract substring of a given length

The following is a program to extract substring from a given string. The substring will be chosen number of charachters strarting from the first character.

The user will be asked to enter a string, and then the number of characters that need to be extracted from it.

The user entered length should not be greater than the length of the original string, thus the string length and requested length are compared and the program stops if requested length is greater than the original string length.



The value of the original string starting from the first character, till the requested length is copied into the new substring. The substring is appended with a null character to indicate end of string.



Full program

#include<iostream>
#include<cstring>
using namespace std ;

int main() { 
int i=0;
char *str,*substr; 
str = new char;
substr = new char;
cout << "Enter  a string,without space, less than 10 characters\n";
cin >> str;
cout << "Enter the number of characters needed to be extracted\n";
int extractLen;
cin >> extractLen;
if(extractLen > strlen(str)) {
 cout << "Can not extract longer than original string\n";
 return -1;
 }
for(i=0;i<extractLen;i++) {
 *(substr+i)=*(str+i);
 }
 *(substr+i) = '\0';

cout << "The substring extracted was \n" << substr<<"\n";
return 0;
}



Save,compile and execute the code.


No comments:

Post a Comment