DEPARTMENTOFSCIENCE&HUMANITIES
Regulation-2025(OBE&CBCSScheme) CourseCode&Name: 1BPLC105E-IntroductiontoCProgramming
Module3
Syllabus
Reading Strings from Terminal, Writing Strings to Screen, Arithmetic Operations on Characters,
Comparison of Two Strings, String-handling Function
Strings
Agroupofcharacterstogetheriscalledstring.
Stringisalwaysenclosedwithindoublequotes(“:”)
String alwaysendswithdelimeter(NULL,’\0’).
Declarationofastring:
Astringisdeclaredlike anarrayofcharacter.
Syntax:datatypestringname[size];
Example:charstr[10];
Initializationofa string:
Syntax:datatypestringname[size]=value;
Example:
1. Charstr[]={‘H’,’e’,’l’, ’l’,’o’,’\0’};
Here compiler will automatically calculate the size based on the number of elements
[Link],in this example 6 memoryslots will be reserved to storethe string variable.
Prepared by: Prof [Link], Dept of AIML, Sri Sairam College of Engineering
DEPARTMENTOFSCIENCE&HUMANITIES
Regulation-2025(OBE&CBCSScheme) CourseCode&Name: 1BPLC105E-IntroductiontoCProgramming
2. Char str[10]=”HELLO”;
The compiler created a character array of size 10, stores the value “HELLO” in it, and
finally terminates the value with a null character. Rest of the elementin the array is
automatically initialized to NULL.
Prepared by: Prof [Link], Dept of AIML, Sri Sairam College of Engineering
DEPARTMENTOFSCIENCE&HUMANITIES
Regulation-2025(OBE&CBCSScheme) CourseCode&Name: 1BPLC105E-IntroductiontoCProgramming
3. Charstr[5]=”HELLO”;
Readingstrings:
Ifwedeclareastringbywriting Char
str[100];
Thenstrcanbereadfromthe userbyusingthree ways:
1. Usingscanffunction.
2. Usinggets()function.
3. Usinggetchar(),getch()orgetche()functionrepeatedly.
Thestringcanbereadusingscanf()bywriting Scanf(“%s”,str);
Themaindrawbackwiththis functionisthatitterminatesassoonasitfindsablank space.
Example: iftheuserenters“Hello world”,thenstrwillcontainonly“Hello”.Thisisbecausethe moment a
blank space is encountered, the string is terminated bythe scanf() function.
Thenextmethodofreading astringis byusinggets()function.
Syntax:gets(str);
gets() is a simple function that overcomes the drawbacks ofscanf().The gets() function takesthe
starting address of the string which will hold the input .
Example:
Prepared by: Prof [Link], Dept of AIML, Sri Sairam College of Engineering
DEPARTMENTOFSCIENCE&HUMANITIES
Regulation-2025(OBE&CBCSScheme) CourseCode&Name: 1BPLC105E-IntroductiontoCProgramming
Writingstrings:
Thestringscanbedisplayed onscreenusing threeways:
1. Usingprintf() function.
2. Usingputs()function.
3. Usingputchar()functionrepeatedly.
Thestringcanbedisplayedusingprintf()bywriting
Printf(“%s”,str);
The next method ofwriting a string is byusing the puts [Link] string can be displayed by
writing
Puts(str);
Puts() is a simple function that overcomes the drawbacks of printf ().the puts() function writes a
line of output on the screen. It terminates the line with a newline character (‘\n’).it returns an
EOF(end of file)(-1)if an error occurs and returns a positive number on success.
DEPARTMENTOFSCIENCE&HUMANITIES
Regulation-2025(OBE&CBCSScheme) CourseCode&Name: 1BPLC105E-IntroductiontoCProgramming
Exampleprogram:
Stringtaxonomy:
Incwecanstoreastringeitherinfixedlength formatorinvariablelength format.
string
Variable length
Fixe
d
Length Delimited
controlled
Fixedlengthstring:
When storing a string in a fixed length format, you need to specify an appropriate size for the
string variable. If the size is too small, then you will not be able to store all the elements in the
string. On the other hand, if the string size is large, then unnecessarily memory space will be
wasted.
Variablelength string:
Thestringcanbeexpandedorcontractedtoaccommodatetheelementsinit.
Example: Declare stringvariable tostore the name of a student. If studenthas alongname of say
20characters,then thestringcanbeexpandedtoaccommodate20characters,on theother
DEPARTMENTOFSCIENCE&HUMANITIES
Regulation-2025(OBE&CBCSScheme) CourseCode&Name: 1BPLC105E-IntroductiontoCProgramming
hand, a student name has only 5 characters, then the string variable can be contracted to store
only 5 characters.
Length–controlledstring:
In length controlled string you need to specifythe number ofcharacters in the string. This count is
used bystring manipulation function to determine the actual length ofthe string variable.
Delimitedstring:
Inthisformat the stringis ended with a [Link] delimiteris then used toidentifythe end of the
string.
For example in English language every sentence is ended with a full-stop, similarly in C we can
use anycharacter suchas comma, semicolon, colon, dash, nullcharacter etc. asthe delimiter ofa
[Link],the nullcharacter is the most commonlyused string delimiter inthe C language.
Stringoperations:
1. Length:
Thenumberofcharactersinthestring constitutesthelengthofthestring.
Example:Length(“Cprogramming isfun”)
Output:return20
Exampleprogram:
#include<stdio.h>
#include<conio.h>
int main()
{
Charstr[100],i=0,length;
Clrscr();
Printf(“\nenterthestring:”);
gets(str);
while(str[i]!=’\0’)
i++;
length=I;
printf(“\\nthelengthofthestringis:%d”,length);
getch();
}
Prepared by: Prof [Link], Dept of AIML, Sri Sairam College of Engineering
DEPARTMENTOFSCIENCE&HUMANITIES
Regulation-2025(OBE&CBCSScheme) CourseCode&Name: 1BPLC105E-IntroductiontoCProgramming
Convertingcharactersofa stringintouppercase:
We have already seen that in memory the ASCII codes are stored instead of the
real value. The ASCII code for A-Z varies from 65 to 91 and ASCII code for a-z
ranges from 97-123.
If we have to convert a lower case character to upper case then we just need to
subs tract 32 from the ASCII value of the character.
ExampleProgram:
#include<stdio.h>
#include<conio.h>
int main()
{
Charstr[100],upper_str[100];
int i=0,j=0;
printf(“\nenterthestring:”);
gets(str);
while(str[i]!=”\0”)
{
if(str[i]>=”a” &&str[i]<=”z”)
upper_str[j]=str[i]-32;
else
upper_str[i]=str[i];
i++;
j++;
Upper_str[j]=”\0”;
Printf(“\nthestringconvertedintouppercaseis:”); Puts(upper_str);
return 0;
Output:
Prepared by: Prof [Link], Dept of AIML, Sri Sairam College of Engineering
DEPARTMENTOFSCIENCE&HUMANITIES
Regulation-2025(OBE&CBCSScheme) CourseCode&Name: 1BPLC105E-IntroductiontoCProgramming
enterthestring: hello
Thestringconvertedintolowercaseis:HELLO
Prepared by: Prof [Link], Dept of AIML, Sri Sairam College of Engineering
DEPARTMENTOFSCIENCE&HUMANITIES
Regulation-2025(OBE&CBCSScheme) CourseCode&Name: 1BPLC105E-IntroductiontoCProgramming
Converting charactersofa stringinto lowercase:
TheASCII codeforA-Zvaries from65to91andthe ASCIIcodefora-zranges from97- 123.
Ifwehaveto convert anuppercasecharacter intolower case, thenwe just needto add32 to its
ASCII value.
ExampleProgram:
#include<stdio.h>
#include<conio.h>
int main()
{
Charstr[100],upper_str[100];
int i=0,j=0;
printf(“\nenterthestring:”);
gets(str);
while(str[i]!=”\0”)
{
if(str[i]>=”a” &&str[i]<=”z”)
lower_str[j]=str[i]-32;
else
lower_str[i]=str[i];
i++;
j++;
lower_str[j]=”\0”;
Printf(“\nthestringconvertedintolowercaseis:”); Puts(lower_str);
return 0;
Output:
Enterthestring:Hello
Prepared by: Prof [Link], Dept of AIML, Sri Sairam College of Engineering
DEPARTMENTOFSCIENCE&HUMANITIES
Regulation-2025(OBE&CBCSScheme) CourseCode&Name: 1BPLC105E-IntroductiontoCProgramming
Thestringconvertedintolowercase is:hello
Prepared by: Prof [Link], Dept of AIML, Sri Sairam College of Engineering
DEPARTMENTOFSCIENCE&HUMANITIES
Regulation-2025(OBE&CBCSScheme) CourseCode&Name: 1BPLC105E-IntroductiontoCProgramming
Concatenatingtwostringsto forma new string:
Ifs1 ands2aretwostrings, thenconcatenationoperationproducesastring whichcontains characters of
s1 followed by the characters of s2.
ExampleProgram:
#include<stdio.h>
#include<conio.h>
int main()
{
Charstr1[100],str2[100],str3[100];
int i=0,j=0;
printf(“\nenterthefirststring:”); gets(str1);
printf(“\nenterthesecondstring:”);
gets(str2);
while(str1[i]!=’\0’)
{
Str3[j]=str1[i];
i++;
j++;
}
i=0;
while(str2[i]!=’\0’)
{
Str3[j]=str2[i];
i++;
j++;
Str3[j]=’\0’;
Printf(“\ntheconcentratedstringis:”);
Puts(str3);
getch();
return0;
Prepared by: Prof [Link], Dept of AIML, Sri Sairam College of Engineering
DEPARTMENTOFSCIENCE&HUMANITIES
Regulation-2025(OBE&CBCSScheme) CourseCode&Name: 1BPLC105E-IntroductiontoCProgramming
Prepared by: Prof [Link], Dept of AIML, Sri Sairam College of Engineering
DEPARTMENTOFSCIENCE&HUMANITIES
Regulation-2025(OBE&CBCSScheme) CourseCode&Name: 1BPLC105E-IntroductiontoCProgramming
Output:
Enterthefirststring:Hello
Enterthe secondstring :Howareyou?
Theconcentratedstringis: Hello,Howareyou?
Appendingstrings:
Appending one string to another involves copying the contentsofthe source string at the
end of the destination string.
Example: ifs1 and s2 are two strings, thenappending s1 to s2means we have to addthe
contents of s1 to s2.
[Link] would leave
the source string s1 unchanged and the destination string s2=s2+s1.
Exampleprogram:
#include
<stdio.h>#include<con
io.h> main()
CharDest_str[100],source_str[50];
int i=0,j=0;
printf(“\nenterthesourcestring:”);
gets(source_str);
printf(“\nenterthedestinationstring:”);
gets(Dest_str);
while(Dest_str[i]!=’\0’)
i++;
while(source_str[j]!=’\0’)
Prepared by: Prof [Link], Dept of AIML, Sri Sairam College of Engineering
DEPARTMENTOFSCIENCE&HUMANITIES
Regulation-2025(OBE&CBCSScheme) CourseCode&Name: 1BPLC105E-IntroductiontoCProgramming
Dest_str[i]=source_str[j];
i++;
Prepared by: Prof [Link], Dept of AIML, Sri Sairam College of Engineering
DEPARTMENTOFSCIENCE&HUMANITIES
Regulation-2025(OBE&CBCSScheme) CourseCode&Name: 1BPLC105E-IntroductiontoCProgramming
j++;
Dest_str[i]=’\0’;
Printf(“\nAfterappending,thedestinationstringis:”); Puts(Dest_str);
getch();
return0;
Output:
Enterthesourcestring:Howareyou?
Enter the destination string:Hi,
Afterappending,thedestinationstringis:Hi,Howareyou?
Comparingtwostrings:
Ifs1ands2aretwo strings thencomparing twostringswillgiveeitheroftheseresults:
1. S1and S2areequal
2 .S1>S2,whenindictionaryorders1willcome afters2.
3 S1<S2,whenindictionaryorders1 precedess2.
Exampleprogram:
#include<stdio.h>
#include<conio.h>
#include<string.h>
main()
Charstr1[50],str2[50];
inti=0,len1=0,len2=0,same=0;
Prepared by: Prof [Link], Dept of AIML, Sri Sairam College of Engineering
DEPARTMENTOFSCIENCE&HUMANITIES
Regulation-2025(OBE&CBCSScheme) CourseCode&Name: 1BPLC105E-IntroductiontoCProgramming
printf(“\nenterthefirst string:”);
gets(str1);
printf(“\nenterthesecondstring”);
gets(str2);
len1=strlen(str1);
len2=strlen(str2);
if(len1==len2)
While(i=len1)
if(str1[i]==str2[i])
i++;
else
break;
if(i==len1)
Same=1;
Printf(“\nthetwo stringsare equal”);
if(len1!=len2)
printf(“\nthetwostringsarenotequal”);
Prepared by: Prof [Link], Dept of AIML, Sri Sairam College of Engineering
DEPARTMENTOFSCIENCE&HUMANITIES
Regulation-2025(OBE&CBCSScheme) CourseCode&Name: 1BPLC105E-IntroductiontoCProgramming
if(same==0)
Prepared by: Prof [Link], Dept of AIML, Sri Sairam College of Engineering
DEPARTMENTOFSCIENCE&HUMANITIES
Regulation-2025(OBE&CBCSScheme) CourseCode&Name: 1BPLC105E-IntroductiontoCProgramming
if(str1[i]>str2[i])
printf(“\nstring1 isgreaterthanstring2”); else
if(str1[i]<str2[i]))
printf(“\nstring2isgreaterthanstring1”);
getch();
return0;
Output:
Enter the first string: Hello
Enterthesecondstring:Hello
The two strings are equal
Reversingastring:
Ifs1=“Hello”, thenreverseofs1=”olleH”.To reverseastringwe just needtoswapthefirst character
withthe last. Second character withthe second last character and so on.
Note:
There is a library function strrev (s1) that reverses allthe characters in the string except
the null character. It is defined in string.h.
Example:
#include<stdio.h>
#include<conio.h>
#include<string.h>
int main()
Prepared by: Prof [Link], Dept of AIML, Sri Sairam College of Engineering
DEPARTMENTOFSCIENCE&HUMANITIES
Regulation-2025(OBE&CBCSScheme) CourseCode&Name: 1BPLC105E-IntroductiontoCProgramming
Prepared by: Prof [Link], Dept of AIML, Sri Sairam College of Engineering
DEPARTMENTOFSCIENCE&HUMANITIES
Regulation-2025(OBE&CBCSScheme) CourseCode&Name: 1BPLC105E-IntroductiontoCProgramming
Charstr[100],reverse_str[100],temp;
int i=0,j=0;
printf(“\nenterthestring”);
gets(str);
j=strlen(str)-1;
while(i<j)
temp=str[j];
str[j]=str[i];
str[i]=temp;
i++;
j--;
Printf(“\nthereversedstringis:”);
Puts(str);
getch();
return0;
Output:
Enterthe string:Hithere
Thereversedstringis:erehtiH
Extractingasubstringfromtheleft ofastring:
In order to extract a substring from the main string we need to copy the content of the string
starting from the first position to the nth position where n is the number of characters to be
Prepared by: Prof [Link], Dept of AIML, Sri Sairam College of Engineering
DEPARTMENTOFSCIENCE&HUMANITIES
Regulation-2025(OBE&CBCSScheme) CourseCode&Name: 1BPLC105E-IntroductiontoCProgramming
extracted.
Example:
Prepared by: Prof [Link], Dept of AIML, Sri Sairam College of Engineering
DEPARTMENTOFSCIENCE&HUMANITIES
Regulation-2025(OBE&CBCSScheme) CourseCode&Name: 1BPLC105E-IntroductiontoCProgramming
Ifs1=”Helloworld”,thensubstr_left(s1,7)=Hellow
Extractingasubstringfromtheright ofastring:
Inorderto extract a substring fromthe right side ofthe main string we need to first calculate the
position.
Example:
Ifs1=”Helloworld”,thensubstr_right(s1,7)=”oworld”
Extracting asubstring fromtheMiddleofa string:
To extract a substring from a given string requires information about three [Link]
the positionofthe first characterofthe substring inthe givenstring and maximumnumber of
characters/length of the substring.
Example:
Str[]=”Welcometotheworldofprogramming”; Then,
Substring(str,15,5)=world
Insertion:
TheinsertionoperationinsertastringS,inthemaintextT,[Link] general syntax of
this operation is : INSERT(text,position,string).
Example:INSERT(“xyzxyz”,3,”AAA”)=”xyzAAAxyz”.
Program:
#include<stdio.>
#include<conio.h>
main()
{
Chartext[100],str[20],ins_text[100]; int
i=0,j=0,k=0,pos;
Prepared by: Prof [Link], Dept of AIML, Sri Sairam College of Engineering
DEPARTMENTOFSCIENCE&HUMANITIES
Regulation-2025(OBE&CBCSScheme) CourseCode&Name: 1BPLC105E-IntroductiontoCProgramming
Printf(“\nenterthemaintext:”); gets
(text);
printf(“\nenterthestring tobeinserted:”);
Prepared by: Prof [Link], Dept of AIML, Sri Sairam College of Engineering
DEPARTMENTOFSCIENCE&HUMANITIES
Regulation-2025(OBE&CBCSScheme) CourseCode&Name: 1BPLC105E-IntroductiontoCProgramming
gets(str);
printf(“\nenterthepositionat whichthestring hastobeinserted:””);
scanf(“%d”,&pos);
ehile(text[i]!=’\0’)
{
if(i==pos)
{
While(str[k]!=’\0’)
{
ins_text[j]=str[k];
j++;
k++;
}
}
else
{
ins_text[j]=text[i];
j++;
} i+
+;
}
ins_text[j]=’\0’;
printf(“\nthenewstringis:”);
puts(ins_text);
getch();
return0;
}
Output:
Enter the main text: How you?
Enterthestringtobeinserted:are
Enterthepositionat whichthestringhasto be inserted:6 The
new string is: How are you?
Indexing:
Prepared by: Prof [Link], Dept of AIML, Sri Sairam College of Engineering
DEPARTMENTOFSCIENCE&HUMANITIES
Regulation-2025(OBE&CBCSScheme) CourseCode&Name: 1BPLC105E-IntroductiontoCProgramming
Indexoperationreturnsthepositioninthestringwherethestringpatternfirstoccurs.
Example:
Prepared by: Prof [Link], Dept of AIML, Sri Sairam College of Engineering
DEPARTMENTOFSCIENCE&HUMANITIES
Regulation-2025(OBE&CBCSScheme) CourseCode&Name: 1BPLC105E-IntroductiontoCProgramming
INDEX(“Welcometotheworldofprogramming”,”world”)=15
Deletion:
The deletion operation deletes a substring from a given [Link] write it as
DELETE(text,position,length).
Example:
DELETE(“ABCDXXXABCD”,5,3)=”ABCDABCD”
Program:
#include<stdio.h>
#include<conio.h>
main()
Chartext[200],str[20],new_text[200];
int i=0,j=0,found=0,k,n=0,copy_loop=0; printf(“\
n enter the main text:”);
gets(text);
fflush(stdin);
printf(“\nenterthestringtobedeleted:”);
gets(str);
fflush9stdin);
while(text[i]!=’\0’)
j=0,found=0,k=i;
while(text[k]==str[j] &&str[j]!=’\0’)
Prepared by: Prof [Link], Dept of AIML, Sri Sairam College of Engineering
DEPARTMENTOFSCIENCE&HUMANITIES
Regulation-2025(OBE&CBCSScheme) CourseCode&Name: 1BPLC105E-IntroductiontoCProgramming
k++;
Prepared by: Prof [Link], Dept of AIML, Sri Sairam College of Engineering
DEPARTMENTOFSCIENCE&HUMANITIES
Regulation-2025(OBE&CBCSScheme) CourseCode&Name: 1BPLC105E-IntroductiontoCProgramming
j++;
if(str[j]==’\0’)
copy_loop=k;
new_text[n]=text[copy_loop];
i++;
copy_loop++;
n++;
}
new_str[n]=’\0’;
printf(“\nthenewstring is:”);
puts(new_text);
getch();
return0;
Output:
Enter the main text :Hello,how are you?
Enterthestringtobedeleted:,howareyou? The
new string is:Hello
Relpacement:
Replacementoperationis used to replace the pattern p1 by anotherpattern t2 . Thisis done by
writing,REPLACE(text,pattern1,pattern2)
Example:
(“AAABBBCCC”,”BBB”,”X”)=AAAXCCC
Prepared by: Prof [Link], Dept of AIML, Sri Sairam College of Engineering
DEPARTMENTOFSCIENCE&HUMANITIES
Regulation-2025(OBE&CBCSScheme) CourseCode&Name: 1BPLC105E-IntroductiontoCProgramming
Miscellaneousstringandcharacterfunctions:
Function Usage Example
isalnum(intc) Checks whethercharacterc is an isalpha(‘A’);
alphanumeric character
isalpha(intc) Checks whether character c is isalpha(‘z’);
an alphanumeric character
iscntrl(intc) Checks whethercharacterc is a Scanf(“%d”,&c);
control character iscntrl(c);
isdigit(intc) Checks whethercharacterc is a isdigit(3);
digit
isgraph() Checks whether character c is isgraph(‘!’);
a graphic or printing
[Link] function
excludesthe white space
character
isprint(intc) Checks whether character c is isprint(‘@’);
a printing [Link]
functionincludesthewhite
spacecharcter
Islower(intc) Checkswhetherthecharacter c Islower(‘k’);
is in lower case
Isupper(intc) Checkswhetherthecharacter c Isupper(‘K’);
is in upper case
Ispunct(intc) Checkswhetherthecharacter c Isspace(‘’)
is a white space character
Isxdigit(intc) Checkswhetherthecharacter c Isxdigi(‘F’);
is a hexadecimal digit
tolower(intc) Convertsthecharactercto lower tolower(‘K’)
case Returns k
toupper(intc) Convertsthecharactercto upper Tolower(‘k’)
case returns K
StringManipulationfunctions:
1. Strcat()function:
Syntax:char*strcat(char*str1,constchar*str2);
Thestrcat()functionappendsthestringpointedbystr2tothe end ofthestring pointedtobystr1.
Example:
Prepared by: Prof [Link], Dept of AIML, Sri Sairam College of Engineering
DEPARTMENTOFSCIENCE&HUMANITIES
Regulation-2025(OBE&CBCSScheme) CourseCode&Name: 1BPLC105E-IntroductiontoCProgramming
#include<stdio.h>
#include<string.h>
Prepared by: Prof [Link], Dept of AIML, Sri Sairam College of Engineering
DEPARTMENTOFSCIENCE&HUMANITIES
Regulation-2025(OBE&CBCSScheme) CourseCode&Name: 1BPLC105E-IntroductiontoCProgramming
int main()
Charstr1[50]=””Programming”;
Char str2[]=”in c”;
Strcat(str1,str2);
Printf(“\nstr1:%s”,str1);
return 0;
Output:
Str1:Programminginc
2. strncat()function:
Syntax:
char*strncat(char*str1,constchar*str2,size_tn);
Thisappendsthestringpointedtobystr2totheendofthestringpointedtobystr1upton characters long.
Example:
#include<stdio.h>
#include<string.h>
int main()
Charstr1[50]=”programming”;
Char str2[]=”in c”;
Strncat(str1,str2,2);
Printf(“\nstr1:%s”,str1);
return 0;
Prepared by: Prof [Link], Dept of AIML, Sri Sairam College of Engineering
DEPARTMENTOFSCIENCE&HUMANITIES
Regulation-2025(OBE&CBCSScheme) CourseCode&Name: 1BPLC105E-IntroductiontoCProgramming
Prepared by: Prof [Link], Dept of AIML, Sri Sairam College of Engineering
DEPARTMENTOFSCIENCE&HUMANITIES
Regulation-2025(OBE&CBCSScheme) CourseCode&Name: 1BPLC105E-IntroductiontoCProgramming
Output:
Str1:programmingin
3. Strchr()function:
Syntax:
Char*strchr(constchar*str,intc);
This function searches for the first occurrence of the character c in the string pointed to by the
argument [Link] functionreturnsa pointer pointing tothe first matching character,or null if no
match was found.
Example:
#include<stdio.h>
#include<string.h>
int main()
Charstr[50]=”programminginc”;
Char *pos;
Pos=strchr(str,’n’);
if(pos)
printf(“\nnisfoundinstratposition%d”,pos); else
printf(“”\nnisnotpresentinthestring”);
return 0;
Output:
nisfoundinstrat position 9
Prepared by: Prof [Link], Dept of AIML, Sri Sairam College of Engineering
DEPARTMENTOFSCIENCE&HUMANITIES
Regulation-2025(OBE&CBCSScheme) CourseCode&Name: 1BPLC105E-IntroductiontoCProgramming
4. Strrchr()function:
Syntax:
Char*strrchr(constchar*str,intc);
Thestrchr()function searchesforthefirstoccurrenceofthecharactercbeginning attherearend and
working towardsthe front in the string pointed to bythe argument str.
Example:
#include<stdio.h>
#include<string.h>
int main()
Charstr[50]=”programminginc”;
Char *pos;
if(pos)
printf(“\nthelast positionofnis:%d”,pos-str); else
printf(“\nnisnotpresentinthestring”);
return 0;
Output:
Thelastpositionofnis:13
5. strcmp()function:
Syntax:
intstrcmp(constchar*str1,constchar*str2);
the strcmp compares the string pointed to by str1 to the string pointed to by [Link] function
returnzero ifthe strings are [Link],it returns a value less thanzero or greater thanzero if
str1 is less than or greater than str2 .
Prepared by: Prof [Link], Dept of AIML, Sri Sairam College of Engineering
DEPARTMENTOFSCIENCE&HUMANITIES
Regulation-2025(OBE&CBCSScheme) CourseCode&Name: 1BPLC105E-IntroductiontoCProgramming
Example:
#include<stdio.h>
#include<string.h>
int main()
Charstr1[10]=”HELLO”;
Char str2[10]=”HEY”;
if(strcmp(str1,str2)==0)
printf(“\nthetwostringsareidentical”); else
printf(“\nthetwostringsarenotidentical”); return
0;
Output:
Thetwo stringsarenotidentical
6. Strcpy()function:
Syntax:
Char*strcpy(char*str1,const char*str2);
This functioncopiesthe stringpointedto bystr2to str1including the [Link] returns
the argument str1.
Example:
Example:
#include<stdio.h>
#include<string.h>
Prepared by: Prof [Link], Dept of AIML, Sri Sairam College of Engineering
DEPARTMENTOFSCIENCE&HUMANITIES
Regulation-2025(OBE&CBCSScheme) CourseCode&Name: 1BPLC105E-IntroductiontoCProgramming
int main()
Charstr1[10]=”HELLO”;
Char str2[10]=”HEY”;
strncpy(str1,str2,2)
printf(“\nstr1:%s”,str1);
return 0;
Output:
HE
7. strlen()function:
Syntax:
Size_tstrlen(constchar*str);
This function calculates the length ofthe string str upto but not including the nullcharacter, i.e the
function returns the number of characters in the string.
Example:
#include<stdio.h>
#include<string.h>
int main()
Charstr[]=”HELLO”;
Printf(“\nlengthofstris:”%d”,strlen(str)); return
0;
Prepared by: Prof [Link], Dept of AIML, Sri Sairam College of Engineering
DEPARTMENTOFSCIENCE&HUMANITIES
Regulation-2025(OBE&CBCSScheme) CourseCode&Name: 1BPLC105E-IntroductiontoCProgramming
Output:
Lengthofstris:5
8. strstr()function:
Syntax:
Char*strstr(constchar*str1,constchar *str2);
[Link] pointer to the first
occurrence ofstr2 [Link] match is found then nullpointer is returned.
Example:
#include<stdio.h>
#include<string.h>
int main()
Charstr1[]=”HAPPYBIRTHDAYTOYOU”;
Charstr2[]=”DAY”;
Char *ptr;
Ptr=strstr(str1,str2));
if(ptr)
printf(“\nsubstringfound”); else
printf(“\nsubstringnotfound”);
return 0;
Output:
Substring found
Arrayofstring:
Prepared by: Prof [Link], Dept of AIML, Sri Sairam College of Engineering
DEPARTMENTOFSCIENCE&HUMANITIES
Regulation-2025(OBE&CBCSScheme) CourseCode&Name: 1BPLC105E-IntroductiontoCProgramming
Stringis anarrayofcharacters.
For example ifwe say, char name[]=”Mohan”, then name isa string(character array) that
has five characters.
Now suppose that there are 20 students in a class and we need a string that stores names
ofall the 20 [Link] we need a string ofstrings or an [Link] an array
ofstrings would store 20 individual [Link] arrayofsring is declared as,
Charname[20][30];
Here the first index will specify how manystrings are needed and the second index specifies the
[Link] hereweallocatespacefor 20 nameswhereeachnamecan be a
maximum of 30 characters long.
Syntax:
Datatypearrayname[rowsize][columnsize]; Memory
representation of an array of strings
Charname[5][10]={“Ram”,”Mohan”,”Shyam”,”Hari”,”Gopal”};
Name[0] R A M \0
M O H A N \0
Name[1]
S H Y A M \0
Name[2]
H A R I \0
Name[3]
atedwithincorrectvalues,itmightleadtomemorycorruption.
Prepared by: Prof [Link], Dept of AIML, Sri Sairam College of Engineering