In: Computer Science
using c++ classes
write program in which CString is used, and give simple and easy
examples in the form of program, to show how to use different
CString function, use comments to explain what happened at that
function.
#include <iostream>
#include <cstring>
using namespace std;
class CstringLL
{
public:
void find_char()
{
//memchr is used to check whether the given char is there in first specified number of characters in a string
char str[]="Hello World";
char c='o';
int count=6;
//if character is found it will return the location of the character to
//be searched otherwise it will return null pointer
if(memchr(str,c,count))
{
cout<<"the character "<<c<<" is present in first "<<count<<" at position "<<memchr(str,c,count);
cout<<"\n";
}
else
{
cout<<"Not found\n";
}
}
void cmp_strings(){
// memcmp() is used to check whether two strings contain same
//specified number of characters
//count defines max no. of bytes to be check
int count=6;
char a[]="Hi my name is aman";
char b[]="Hi my name is rahul";
//if character in a at specifies count is greater then b then return positive value..
//if character in a is smaller then in characters of b at specified count return negative value else return 0 when two string are same at specified count
int r=memcmp(a,b,count);
if(r==0){cout<<"two string has same first "<<6<<" characters";}
}
void cpy_str(){
cout<<"\n";
int a[5]={1,2,3,4,5};
int b[5];
memcpy(b,a,sizeof(int)*3);
//copying only specified number i.e. 3 from array a in another array b
for(int i=0;i<3;i++) cout<<b[i]<<" ";
}
void compare()
{
char a[]="Hello";
char b[]="by";
if(strcmp(a,b))
{
cout<<"\ndifferent string";
}
else
cout<<"\n two string are same";
}
void find_length(char s[10])
{
cout<<"\n";
cout<<strlen(s);
}
void char_ntimes(){
//storing particular character in specified times
char d[10];
char c='o';
memset(d,c,6);
cout<<"\n";
cout<<d;
cout<<" storing char 6 times";
}
void split_string(){
// splitting string on the basis of delimeter
char n[]="apple mango orange pineapple";
char delimeter[]=" ";
char *r=strtok(n,delimeter);
cout<<"\n";
while(r)
{
cout<<r<<" ";
r=strtok(NULL,delimeter);
}
}
};
int main()
{
CstringLL cl;
cl.find_char(); // search for char
cl.cmp_strings(); //compare strings
cl.cpy_str(); // copy specified amount of data
cl.compare();
char s[]="Hello";
cl.find_length(s);//find length of string
cl.char_ntimes();// storing character n times in destination string
cl.split_string();//spliting the string on the basis of delimeter
return 0;
}
Screenshot-