0% found this document useful (0 votes)
48 views63 pages

Strings PART1

Uploaded by

omkeshri21
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
48 views63 pages

Strings PART1

Uploaded by

omkeshri21
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 63

CSE101-Lec#23

Strings

©LPU CSE101 C Programming


Outline
• Introduction to string
– Declaration
– Initialization
• Reading and writing strings
– functions of the standard input/output library (stdio.h)
• Processing of strings.
• String Manipulation Functions from the String Handling Library
• Comparing strings
• Determining the length of string
• All string operations without inbuilt functions
• Other programs related to strings

©LPU CSE101 C Programming


Fundamentals of strings
• Strings
– Array of characters treated as a single unit called
string:
• Can include letters, digits and special characters (*, /,
$)
– String literal (string constant) - written in double
quotes
• “Lovely Professional University."

©LPU CSE101 C Programming


What is a String??
• String is a collection of characters terminated by
null character
• Strings are arrays of characters
– String is a pointer to first character (like array)
– Value of string is the address of first character
• Each element of the string is stored in a
contiguous memory locations.
• Terminated by a null character(‘\0’) which is
automatically inserted by the compiler to indicate
the end of string.

©LPU CSE101 C Programming


String Definition
• They are defined as
char array_name[size];
e.g. char carname[30];
or char *carname;
• It defines an array name and reserves 30 bytes for
storing characters and single character consumes
1 bytes each.
• Since the last byte is used for storing null
character so total number of character specified
by the user cannot exceed 29.

©LPU CSE101 C Programming


String Initialization
• String Initialization
– Two ways:
– Define as a character array or a variable of type
char *
char color[] = "blue"; //char array
Or char color[] = { 'b', 'l', 'u', 'e', '\0' };
char *colorPtr = "blue"; //pointer variable
– Remember that strings represented as character
arrays end with '\0'
b •l color has
u 5 elements
e \0 b l u e \0
color Temporary

©LPU CSE101 C Programming


*colorPtr
String Input/Output
• Inputting strings
– Use scanf.
scanf("%s", word);
• Copies input into word[]
• Do not need & (because a string is a pointer)
– Remember to leave last place in the array for '\0‘.
– Because array knows no bounds the string written
beyond char array size will overwrite the data in
memory.
• Displaying strings
– Use printf.
printf("%s", word);

©LPU CSE101 C Programming


#include <stdio.h>
int main()
Program to read
{ and display
char carname[20]; //string char array
printf(“Enter the name of your car: ");
string
scanf("%s", carname);// to display the input
printf(“\nName of car is %s”, carname);
} //end main

Enter the name of your car: XUV500


Name of car is XUV500
Output

©LPU CSE101 C Programming


How?
• The last program will print only a single word
not the sentences with white spaces?
• That is if input is
Lovely Professional University
• Output will be: use gets and puts
Lovely
• So how to print:
Lovely Professional University

©LPU CSE101 C Programming


Standard I/O Library Functions
• List of functions in #include<stdio.h>
• Used for string input/output functions.
Function Description
gets( char *s ); Inputs characters from the standard input into the
array s until a newline or end-of-file character is
encountered. A terminating null character is
appended to the array.
puts( const char *s ); Prints the string s followed by a newline
character.

©LPU CSE101 C Programming


#include <stdio.h>
int main()
Program to print
{ strings with
char name[100]; //string char array
puts(“\nEnter a string:”);
white spaces
gets(name); //to input string with space using library
printf(“\nString is:”)
puts(name); //to output const string functions
}//end main

Enter a string:
Lovely Professional University
Output
String is:
Lovely Professional University
©LPU CSE101 C Programming
Drawback of gets():
gets() has been removed from c11. So it might give you a
warning when implemented.
We see here that it doesn’t bother about the size of the array.
So, there is a chance of Buffer Overflow.

Alternative of gets():
To overcome the above limitation, we can use fgets as :
Syntax : char *fgets(char *str, int size, FILE *stream)
Example : fgets(str, 20, stdin); as here, 20 is MAX_LIMIT
according to declaration.
#include <stdio.h>
#define MAX_LIMIT 20
int main()
{
char str[MAX_LIMIT];
fgets(str, MAX_LIMIT, stdin);
printf("%s", str);
return 0;
}

©LPU CSE101 C Programming


Multiple words input using scanf():
1)
#include <stdio.h>
int main()
{
char str[20];
scanf("%[^\n]%*c", str);
printf("%s", str);
return 0;
}
Here, [] is the scanset character. ^\n tells to take input until newline
doesn’t get encountered. Then, with this %*c, it reads newline
character and here used * indicates that this newline character is
discarded.
2)
#include <stdio.h>
int main() {
char str[100];
scanf("%[^\n]s",str);
printf("%s",str);
return 0;
}

©LPU CSE101 C Programming


#include <stdio.h>
int main()
Program to print
{ strings character
char name[]=“Hello”; //string char array
int i=0;
by character
while(name[i]!='\0') //untill null character using loop.
{
printf("%c",name[i]);
i++;
}//end while
}//end main

Hello
Output

©LPU CSE101 C Programming


String Handling Library
• Functions defined in #include<string.h>
• String handling library provides many useful
functions:
– Manipulate string data(copy and concatenate)
– Comparing strings
– Determine string length

©LPU CSE101 C Programming


String Manipulation Functions(or Functions in string library)

©LPU CSE101 C Programming


More functions in string library

• strlen()-It is used to find the length of string


without counting the null character
• strrev()-It is used to display the reverse of a
string
• strlwr()-Converting a string from upper to
lower case
• strupr()-Converting a string from lower to
upper case

©LPU CSE101 C Programming


strcpy() and strncpy()

• strcpy() copies the entire second argument string into first


argument.
strcpy( s1, s2);
• strncpy() copies the first n characters of second string
argument into first string argument.
strncpy( s1, s2, 4);
– A null character ('\0') is appended explicitly to first
argument, because the call to strncpy in the program does
not write a terminating null character.
– The third argument is less than the string length of the
second argument.

©LPU CSE101 C Programming


Examples
//strcpy() function //strncpy()
#include<stdio.h> #include<stdio.h>
#include<string.h> #include<string.h>
int main() int main()
{ {
//strcpy function char str1[15],str2[15];
char ori[20],dup[20]; int n;
char *z; printf("\nEnter Source String:");
printf("\n Enter your name:"); gets(str1);
gets(ori); printf("\nEnter Destination String:");
z=strcpy(dup,ori); gets(str2);
printf("Original String is: printf("Enter number of characters to
%s",ori); copy in destination string:");
printf("\nDuplicate String is: scanf("%d",&n);
%s",dup); strncpy(str2,str1,n);
printf("\n Value of z is:%s",z); printf("Source string is:%s",str1);
return 0; printf("\nDestination String is:
} %s",str2);
return 0;
}

©LPU CSE101 C Programming


strcat()
• Function strcat appends its second argument
string to its first argument string.
strcat( s1, s2);
• The array used to store the first string should be large
enough to store
– the first string
– the second string and
– the terminating null character copied from the second
string.

©LPU CSE101 C Programming


strncat()
• Function strncat appends a specified number of
characters from the second string to the first
string.
strncat( s1, s2, 6)
• A terminating null character is automatically
appended to the result.

©LPU CSE101 C Programming


Examples
//strcat //strncat
#include<stdio.h> #include<stdio.h>
#include<string.h> #include<string.h>
int main() int main()
{ {
char str1[20],str2[10]; char str1[20],str2[10];
printf("\n Enter first string:");
int n;
gets(str1);
printf("\n Enter second string:");
printf("\n Enter first string:");
gets(str2); gets(str1);
strcat(str1,str2); printf("\n Enter second string:");
printf("\n String after concatenation: gets(str2);
%s",str1); printf("\n Enter number of
return 0; characters you want to combine:");
} scanf("%d",&n);
strncat(str1,str2,n);
printf("\n String after
concatenation:%s",str1);
return 0;
}

©LPU CSE101 C Programming


Comparison Functions of the String
Handling Library
• Comparing strings
– Computer compares numeric ASCII codes of
characters in string
– strcmp() Compares its first string argument with its
second string argument, character by character.
– Function strncmp() does not compare characters
following a null character in a string.

©LPU CSE101 C Programming


strcmp()
int strcmp( const char *s1, const char *s2 );
– Compares string s1 to s2
– Returns
• a negative number if s1 < s2,
• zero if s1 == s2
• a positive number if s1 > s2

©LPU CSE101 C Programming


strncmp()
int strncmp( const char *s1, const char *s2, int n);
– Compares up to n characters of string s1 to s2
• a negative number if s1 < s2,
• zero if s1 == s2
• a positive number if s1 > s2

©LPU CSE101 C Programming


Examples // strncmp
//strcmp #include<stdio.h>
#include<stdio.h> #include<string.h>
#include<string.h>
int main()
int main()
{
{
char str1[20],str2[10];
char str1[20],str2[10];
int x,n;
int x;
printf("\n Enter first string:");
printf("\n Enter first string:");
gets(str1); gets(str1);
printf("\n Enter second string:"); printf("\n Enter second string:");
gets(str2); gets(str2);
x=strcmp(str1,str2); printf("\n Enter no. of characters to compare:");
if(x==0) scanf("%d",&n);
{ x=strncmp(str1,str2,n);
printf("\n Strings are equal"); if(x==0)
} {
else if(x>0) printf("\n Strings are equal");
{ }
printf("\n First string is greater else if(x>0)
than second string(strings are not equal)"); {
} printf("\n First string is greater than
else second string(strings are not equal)");
{ }
printf("\n First string is less than else
second string(strings are not equal)");
{
}
printf("\n First string is less than
return 0; second string(strings are not equal)");
}
}
return 0;
©LPU CSE101 C Programming }
stricmp()[Ignore case], stricmp will ignore the case

#include<stdio.h>
int main()
{
char str1[20],str2[10];
int x;
printf("\n Enter first string:");
gets(str1);
printf("\n Enter second string:");
gets(str2);
x=stricmp(str1,str2);
if(x==0)
{
printf("\n Strings are equal");
}
else if(x>0)
{
printf("\n First string is greater than second string(strings are not equal)");
}
else
{
printf("\n First string is less than second string(strings are not equal)");
}
return 0;
}
//consider str1(HELLO) and str2(hello) and if we apply stricmp on these strings, then 0 will be returned, as
strings are equal

©LPU CSE101 C Programming


Determining the length of string
strlen()
• Function strlen in #include<string.h>
• Function strlen() takes a string as an
argument and returns the number of
characters in the string
– the terminating null character is not included in
the length

©LPU CSE101 C Programming


Example
#include<stdio.h>
#include<string.h>
int main()
{
char str[]="Hello";
printf("\n Length of the given string is:%d",strlen(str));
return 0;
}

©LPU CSE101 C Programming


strrev()-Example
#include<stdio.h>
#include<string.h>
int main()
{
char s[100]="Hello";
printf("%s",strrev(s));
return 0;
}

©LPU CSE101 C Programming


strlwr(),strupr()-Examples
#include<stdio.h>
#include<string.h>
int main()
{
char s[]="hello";
strupr(s);
puts(s);
strlwr(s);
puts(s);
return 0;
}

©LPU CSE101 C Programming


All string operations without inbuilt functions

• Copying one string to another


• Finding length of a string
• Concatenation(or Combining) of two strings
• Comparing two strings
• Displaying reverse of a number
• Checking whether a given string is palindrome or not
• Converting all characters of a given string from
lowercase to uppercase
• Converting all characters of a given string from
uppercase to lowercase

©LPU CSE101 C Programming


WAP to copy one string to another without using strcpy()/or
inbuilt function
#include<stdio.h>
int main() {
char s1[100], s2[100];
int i;
printf("\nEnter the string :");
gets(s1);//Hello
i = 0;
while (s1[i] != '\0') {
s2[i] = s1[i];
i++;
}
s2[i] = '\0';
printf("\nCopied String is %s ", s2);
return (0);
}

©LPU CSE101 C Programming


WAP to find the length of a string without using strlen()/ or
inbuilt function
#include<stdio.h>
int main()
{
char x[100];
int i=0;
printf("\n Enter String:");
gets(x);
while(x[i]!='\0')
{
i++;
}
printf("\n Length of the string is:%d",i);
return 0;
}

©LPU CSE101 C Programming


WAP to concatenate(or combine) two strings without using
strcat/ or inbuilt function
#include<stdio.h> while(str2[i]!='\0')
int main() {
{ str3[j]=str2[i];
char i++;
str1[100],str2[100],str3[200]; j++;
int i=0,j=0; }
printf("\n Enter the first str3[j]='\0';
string:"); printf("\n The concatenated
gets(str1); string is:");
printf("\n Enter the second puts(str3);
string:"); return 0;
gets(str2); }
while(str1[i]!='\0')
{
str3[j]=str1[i];
i++;
j++;
}
i=0;

©LPU CSE101 C Programming


WAP to compare two strings without using strcmp()/ or inbuilt
#include <stdio.h> function while (i<length)
#include<string.h> {
int main () if( str1 [i] == str2 [i])
{
{
i++;
// declare variables
continue;
char str1 [30], str2 [30]; }
int i = 0, flag=0 ,length1, length2, length; if( str1 [i] < str2 [i])
// take two string input {
printf ("Enter string1:"); flag = -1;
gets (str1); break;
printf ("\nEnter string2:"); }
gets (str2); if( str1 [i] > str2 [i])
//length of both string {
length1 = strlen (str1);
flag = 1;
break;
length2 = strlen (str2);
}
if(length1>length2)
}
length=length1; if (flag == 0)
else printf ("\nBoth strings are equal ");
length=length2; if(flag == -1)
printf ("\nstring1 is less than string2 ");
• if( flag == 1)
printf ("\nstring1 is greater than string2 ");
return 0;
}

©LPU CSE101 C Programming


Dry running

©LPU CSE101 C Programming


WAP to display the reverse of a given string without
strrev()/ or inbuilt function
#include<stdio.h>
#include<string.h>
int main() {
char str[100], temp;
int i, j;
printf("\nEnter the string :");
gets(str);
i = 0;
j = strlen(str) - 1;
while (i < j) {
temp = str[i];
str[i] = str[j];
str[j] = temp;
i++;
j--;
}
printf("\nReverse string is :%s", str);
return (0);
}

©LPU CSE101 C Programming


Dry running

©LPU CSE101 C Programming


WAP to check whether the given string is palindrome or
not(without using strrev())
#include<stdio.h> if(strcmp(str1,str)==0)
#include<string.h> {
int main() { printf("\n Given String is Palindrome");
char str[100], temp; }
char str1[100]; else
int i, j; {
printf("\nEnter the string :"); printf("\n Not a Palindrome");
gets(str); }
i = 0; return (0);
j = strlen(str) - 1; }
strcpy(str1,str);
while (i < j)
{
temp = str[i];
str[i] = str[j];
str[j] = temp;
i++;
j--;
}

©LPU CSE101 C Programming


WAP to convert all characters of a given string into uppercase
without using strupr()/or inbuilt function
#include<stdio.h>
#include<string.h>
int main()
{
char str1[10];
int i,len;
printf("Enter any string \t");
gets(str1);
len=strlen(str1);
for(i=0;i<len;i++)
{
if(str1[i]>='a' && str1[i]<='z')

str1[i]=str1[i]-32;
}
puts("string in upper is");
puts(str1);
return 0;
}

©LPU CSE101 C Programming


WAP to convert all characters of a given string into lowercase without
using strlwr()/or inbuilt function
#include<stdio.h>
#include<string.h>
int main()
{
char str1[10];
int i,len;
printf("Enter any string \t");
gets(str1);
len=strlen(str1);
for(i=0;i<len;i++)
{

if(str1[i]>='A' && str1[i]<='Z')


str1[i]=str1[i]+32;
}
puts("string in lower is");
puts(str1);
return 0;
}

©LPU CSE101 C Programming


More programs on strings

©LPU CSE101 C Programming


WAP to sort the characters of a given string into ascending
order
#include<stdio.h>
#include<string.h>
int main()
{
char s[10],t;
int n,i,j;
printf("\n Enter String:");
gets(s);
n=strlen(s);
for(i=0;i<n-1;i++)
{
for(j=0;j<n-i-1;j++)
{
if(s[j]>s[j+1])
{
t=s[j];
s[j]=s[j+1];
s[j+1]=t;
}
}
}
printf("%s",s);
}

©LPU CSE101 C Programming


WAP to count vowels in a given string
#include<stdio.h>
int main()
{

char x[100];
int i=0,count=0;
printf("\n Enter the string:");
gets(x);
while(x[i]!='\0')
{
if(x[i]=='a'||x[i]=='e'||x[i]=='i'||x[i]=='o'||x[i]=='u'||x[i]=='A'||x[i]=='E'||x[i]=='I'||
x[i]=='O'||x[i]=='U')
{
count++;
}
i++;
}
printf("\n Number of vowels in the string are:%d",count);
return 0;
}

©LPU CSE101 C Programming


WAP to traverse all characters of a given string using pointer to character

#include<stdio.h>
int main()
{
char *g="C Programming";
int length=0,i=0;
while(*g!='\0')
{
printf("%c",*g);//Value at address
g++;//Pointer is incremented by 1 after each iteration
length++;//Variable for counting length
}
printf("\nLength of the string is:%d",length);
return 0;
}

©LPU CSE101 C Programming


WAP to count total no. of characters and words in a given string

#include<stdio.h>
int main()
{
char x[100];
int i=0,length=0,c=0,w=1;
printf("\n Enter String:");
gets(x);
while(x[i]!='\0')
{
if(x[i]==' ' && x[i+1]!=' ')
{
w++;
}
c++;
i++;
}
printf("\n Total number of characters are:%d, and no. of words are:%d",c,w);
return 0;
}

©LPU CSE101 C Programming


WAP to demonstrate array of strings in C
#include<stdio.h>
int main()
{
char names[5][10];
int i,n;
printf("\n Enter the number of students:");
scanf("%d",&n);
fflush(stdin);
for(i=0;i<n;i++)
{
printf("\n Enter the name of student %d: ",i+1);
gets(names[i]);
}
printf("\n Names of the students are:\n");
for(i=0;i<n;i++)
puts(names[i]);
return 0;
}

©LPU CSE101 C Programming


WAP to traverse a string character by character

#include <stdio.h>
int main()
{
char name[]="Hello World"; //string char array
int i=0;
while(name[i]!='\0') //untill null character
{
printf("%c\n", name[i]);
i++;
}//end while
}//

©LPU CSE101 C Programming


WAP to replace all spaces in a given string with ‘$’[Example for character
replacement]
#include<stdio.h>
int main()
{
char x[100];
int i=0;
printf("\n Enter the string:");
gets(x);
while(x[i]!='\0')
{
if(x[i]==' ')
{
x[i]='$';//Character replacement
}
i++;
}
printf("\n String after character replacement is:%s",x);
return 0;
}

©LPU CSE101 C Programming


Output-1??
#include<stdio.h>
int main()
{
char str[]="Practice MCQ";
printf("\n%d",sizeof(str));
return 0;
}
A. 13
B. 12
C. 11
D. 1

©LPU CSE101 C Programming


Output-2??
#include<stdio.h>
int main()
{
char str[]="Program";
printf("%c",str[7]);
return 0;
}
A. m
B. Program
C. Compile time error
D. Nothing will be visible

©LPU CSE101 C Programming


Output-3??
#include<stdio.h>
int main()
{
char str1[]="Good";
char str2[5];
str2=str1;
printf("%s",str2);
return 0;
}
A. Good
B. Garbage value
C. Compile time error
D. Nothing will be visible

©LPU CSE101 C Programming


Output-4??

#include<stdio.h>
int main()
{
char str1[]="Good";
char *str2;
str2=str1;
puts(str2);
return 0;
}
A. Good
B. Garbage value
C. Compile time error
D. Nothing will be visible

©LPU CSE101 C Programming


Output-5??
#include<stdio.h>
#include<string.h>
int main()
{
char str[20]="Example";
printf("%d %d",sizeof(str),strlen(str));
return 0;
}
A. 7 7
B. 20 20
C. 20 7
D. 20 8

©LPU CSE101 C Programming


Output-6??
#include<stdio.h>
#include<string.h>
int main()
{
char str1[20]="Example";
char str2[30]="Exam";
if(strncmp(str1,str2,4))
printf("\nHello");
else
printf("\nWorld");
return 0;
}
A. Hello
B. World
C. Nothing will be printed
D. Compile time error

©LPU CSE101 C Programming


Output-7??
What will be the output of the program ?
#include<stdio.h>
#include<string.h>
int main()
{
char str1[20] = "Hello", str2[20] = " World";
printf("%s\n", strcpy(str2, strcat(str1, str2)));
return 0;
}
A. Hello
B. World
C. Hello World
D. WorldHello

©LPU CSE101 C Programming


Output-8??
In below program, what would you put in place of “?” to print
“Quiz”?
#include <stdio.h>
int main()
{
char arr[] = "HelloQuiz";
printf("%s", ?);
return 0;
}
A. arr
B. (arr+5)
C. (arr+4)
D. Not possible

©LPU CSE101 C Programming


Question-9

Which of the following C code snippet is not valid?

(A) char* p = “string1”; printf(“%c”, *++p);

(B) char q[] = “string1”; printf(“%c”, *++q);

(C) char* r = “string1”; printf(“%c”, r[1]);

(D) None of the above


Output-10 ??

#include<stdio.h>

int main()

printf(8+"C Programming\n");

return 0;

A. mming

B. ming

C. amming

D. gramming
Output-11 ??

//Assume unsigned integer takes 4 bytes


#include <stdio.h>
int main()
{
char *str1 = "Hello";
char str2[] = "Hello";
printf("sizeof(str1) = %d, sizeof(str2) = %d",sizeof(str1), sizeof(str2));
return 0;
}
A. sizeof(str1) = 8, sizeof(str2) = 6
B. sizeof(str1) = 4, sizeof(str2) = 6
C. sizeof(str1) = 4, sizeof(str2) = 4
D. sizeof(str1) = 6, sizeof(str2) = 4
Output-12 ??

Predict the output of the following program:

#include <stdio.h>

int main()

char str[] = "%d %c", arr[] = "HelloWorld";

printf(str, 0[arr], 2[arr + 3]);

return 0;

A. 72 W

B. H W

C. W H

D. Compile-time error
Output-13??
#include <stdio.h>
int main()
{
char *str="WORLD";
while(*++str)
{
printf("%c",*str);
}
return 0;
}
A. ORLD
B. WORLD
C. RLD
D. Compile time error

You might also like