You are on page 1of 4

Lecture-29

//String Concatenation

#include <iostream>
#include <cstring>
using namespace std;
void strConcat(char*, char*);
int main()
{ char a[50],b[50];
cout<<" Enter first string: ";
cin.getline(a,50);
cout<<" Enter second string: ";
cin.getline(b,50);
strConcat(a,b);
cout<<a;
return 0;
}
void strConcat(char* p, char* s)
{ while(*p)
p++;
while(*s)
{ *p=*s;
p++;
s++;
}
*s='\0';
}

//String Comparison program (= or !=)

#include<iostream>
using namespace std;
int main()
{
char s1[50], s2[50];
int i=0, flag=0;
cout<<"Enter the First String: ";
cin>>s1;
cout<<"Enter the Second String: ";
cin>>s2;

while(s1[i]!='\0' || s2[i]!='\0')
{
if(s1[i]!=s2[i])
{
flag = 1;
break;
}
i++;
}
if(flag==0)
cout<<"\n Strings are Equal";
else
cout<<"\n Strings are not Equal";
cout<<endl;
return 0;
}

//String comparison (= or < or >)


#include<iostream>
using namespace std;
int main()
{
char s1[50], s2[50];
int i=0, flag=0;
cout<<"Enter the First String: ";
cin>>s1;
cout<<"Enter the Second String: ";
cin>>s2;
while(s1[i]!='\0' || s2[i]!='\0')
{ if(s1[i]!=s2[i])
{ if(s1[i]<s2[i])
{ flag=-1;break;}
else { flag=1; break;}
}
i++;
}
if(flag==0)
cout<<"\n Strings are Equal";
else if(flag==-1)
cout<<"\n string1 < string 2";
else cout<<"\n string1 > string 2";
cout<<endl;
return 0;
}

////String comparison (= or < or >) using functions


int strComp(char*,char*);
int main()
{ char s1[50], s2[50];
int i=0, flag=0;
cout<<"Enter the First String: ";
cin>>s1;
cout<<"Enter the Second String: ";
cin>>s2;
flag=strComp(s1,s2);
if(flag==0)
cout<<"\n string 1= string 2";
else if(flag==-1)
cout<<"\n string1 < string 2";
else cout<<"\n string1 > string 2";
return 0;
}
int strComp(char* s1,char*s2)
{ int i=0,flag=0;
while(s1[i]!='\0' || s2[i]!='\0')
{
if(s1[i]!=s2[i])
{
if(s1[i]<s2[i])
{ flag=-1;break;}

else { flag=1; break;}


}
i++;
}
return flag;
}

// Sorting of strings using our strComp function

#include <iostream>
#include<cstring>
using namespace std;
int strComp(char*,char*);
int main()
{
int k,num,i,j; char name[30][60];
char temp[60];
cout<<"enter number of names to be sorted:";
cin>>num;
cout<<"enter the names : \n";
for(i=0;i<num;i++)
cin>>name[i];

for(i=0;i<num;i++)
{ for(j=0;j<num-1;j++)
{ k=strComp(name[j],name[j+1]);
if(k==1)
{ strcpy(temp,name[j]);
strcpy(name[j],name[j+1]);
strcpy(name[j+1],temp);
}
}
}
cout<<"names in sorted order: \n";
for(i=0;i<num;i++)
cout<<name[i]<<endl;
return 0;
}
int strComp(char* s1,char*s2)
{ int i=0,flag=0;
while(s1[i]!='\0' || s2[i]!='\0')
{ if(s1[i]!=s2[i])
{
if(s1[i]<s2[i])
{ flag=-1;break;}
else { flag=1; break;}
}
i++;
}
return flag;

You might also like