Write a menu driven program to a) Find the length of a string b) concatenate two strings c) to extract a substring from a given string d) Finding and replacing a string by another string in a text (Use pointers and user-defined functions)
#include
#include
#include
#include
#include
class
string_manipulation
{
public:
void
lenstr(char *);
void
concatenate(char *, char *, char *);
int
str_rep(char *, char *, int c[]);
void
extract();
};
void
string_manipulation::lenstr(char *p)
{
int
len = 0;
while
(*p++)
{
len
++;
}
cout
<< "The length of the string is : " <
}
void
string_manipulation::concatenate(char *s1, char *s2, char *rs)
{
while
(*s1)
{
*rs++
= *s1++;
}
while
(*s2)
{
*rs++
= *s2++;
}
*rs
= '\0';
}
void
string_manipulation::extract()
{
char
str1[ ] = "String1", str2[ ] = "String2" ;
int
i, j, s, e;
clrscr();
cout
<< "Enter a string : " ;
gets(str1);
fflush(stdin);
cout
<< "Enter the starting points : " ;
cin
>> s;
cout
<< "Enter the end points of string : " ;
cin
>> e;
fflush(stdin);
for
(i=s-1, j=0 ;i<=e ;i++, j++ )
{
str2[j]
= str1[i];
}
str2[j]
= '\0';
cout
<< str2;
getch();
}
int
index_str1, index_str2, k;
int
c[100];
int
string_manipulation::str_rep(char *s1, char *s2, int c[ ])
{
int
count = 0;
int
i = 0,j , l = 0;
char
s3[' '];
cout
<< "Enter the string to be replaced : " ;
gets(s3);
for
(index_str1=0 ;s1[index_str1] ;index_str1++ )
{
for
(index_str2=index_str1, k=0
;(s1[index_str2]==s2[k])&&(s1[index_str1]) ;index_str2++, k++
)
{
if
(!s2[k+1])
{
count++;
c[l++]
= index_str1;
for
(j=index_str1 ;j
{
s1[j]
= s3[i++];
}
s1[j]
= '\0';
cout
<< s1;
}
}
}
return(count);
}
void
main()
{
string_manipulation
obj;
int
ch;
clrscr();
cout
<< "\nChoose any given option : ";
cout
<< "\n\t 1. String length" ;
cout
<< "\n\t 2. String concatenation" ;
cout
<< "\n\t 3. Extract string from given string";
cout
<< "\n\t 4. Find and replace string" ;
cout
<< "\n\t 5. Exit" ;
cout
<< "\n\nEnter your choice : " ;
cin
>> ch;
switch
(ch)
{
case
1: char str[80];
cout << "Enter a string : " ;
gets(str);
obj.lenstr(str);
break;
case
2: char str1[128];
char str2[128];
char output_str[257];
cout << "Enter the first sting : " ;
gets(str1);
cout << "\nEnter the second string : " ;
gets(str2);
obj.concatenate(str1, str2, output_str);
cout << "The concatenate string is : " ;
cout << output_str;
break;
case
3: obj.extract();
break;
case
4: char *s;
int c[100], count;
char s1[' '], s2[' '];
clrscr();
cout << "Enter the first sting : " ;
gets(s1);
cout << "Enter the sting to search : " ;
gets(s2);
obj.str_rep(s1, s2, c);
break;
case
5: exit(0);
default:
cout << "\nInvalid choice" ;
}
getch();
}
Comments
Post a Comment