Week 20 solutions
20a) Write a C++ program to write a function void to_lower(char* s)
that replaces all uppercase characters.
Don't use any standard library functions.
Program:
#include<iostream>
#include<cstring>
#include<cstdio>
using namespace std;
void to_lower(char* s);
int main()
{
string st;
char* s;
cout<<"Enter any string\n";
cin>>st;
s = strdup(st.c_str());
to_lower(s);
cout<<"\n Original string is :"<<st;
cout<<"\n modified string is :"<<s;
return 0;
}
void to_lower(char* s)
{
for(int i=0;s[i]!='\0';i++)
s[i] = (s[i]>='A' && s[i]<='Z')?(s[i]+32):s[i];
}
output:
Enter any string
C++PROGRAMMING
Original string is :C++PROGRAMMING
modified string is :c++programming
20b) b) Write a C++ program to write a function,char* findx(const char* s, const char* x),
that finds the first occurrence of the string x in s.
Program:
#include<iostream>
#include<cstring>
#include<cctype>
using namespace std;
char* findx(const char* s,const char* x);
int main()
{
string st,st1;
char* a;
char* b;
cout<<"Enter any string\n";
getline(cin,st);
cout<<"Enter string to search\n";
cin>>st1;
a = strdup(st.c_str());
b = strdup(st1.c_str());
findx(a,b);
return 0;
}
char* findx(const char* s,const char* x)
{
char* check=new char[10];
int j=0;
int count=0;
for(int i=0;i<=strlen(s);i++)
{
if(isspace(s[i])||s[i]=='\0')
{
check[j]='\0';
j=0;
if(strcmp(check,x)==0)
{
cout<<x<<" is present in the string at index :"<<i-strlen(x)<<endl;
count++;
}
}
else
check[j++]=s[i];
}
if(count==0)
cout<<x <<" is not present in the string \n";
}
output:
Enter any string
Ramu is a naughty boy and he is also intelligent
Enter string to search
is
is is present in the string at index :5
is is present in the string at index :29
C:\Users\Personal\Desktop>
No comments:
Post a Comment