0% found this document useful (0 votes)
28 views

Strings Final

Uploaded by

akhilkc99999
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
28 views

Strings Final

Uploaded by

akhilkc99999
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 57

STRINGS

Agenda
• Introduction

• Declaration & Initialization


• Reading & Printing Strings
• Arithmetic Operations on characters
• String Handling Functions
• Table of Strings
• References
Introduction
• String can be represented as a single-dimensional character
type array.
• C language does not provide the intrinsic string types.
• Strings in C are group of characters, digits, and symbols
enclosed in quotation marks or simply we can say the string
is declared as a “character array”.
• The end of the string is marked with a special character, the ‘\0’
(Null character), which has the decimal value 0.
• There is a difference between a character stored in memory
and a single character string stored in a memory.
• The character requires only one byte whereas the single
character string requires two bytes (one byte for the
character and other byte for the delimiter).
• The string functions operate on null-terminated arrays of
characters and require the header <string.h>.
Introduction
• A string is an array of characters.
• Any group of characters defined between double quotation marks is a constant
string
–EXAMPLE: “Man is obviously made to think.”
• To include a double quote in the string to be printed, use a back slash.
– EXAMPLE: printf(“Well Done !”);
– OUTPUT: Well Done!
– EXAMPLE: printf(“\”Well Done!\””);
– OUTPUT: “Well Done!”
Introduction
• Common operations performed on strings are:
– Reading and writing strings
– Combining together
– Copying one ststrings ring to another
– Comparing strings for equality
– Extracting a portion of a string
– Reversing a string
Declaration
•Thesyntax is: char string-name[size];
•Examples:

char name[20];
char address[25];
char city[15];
DECLARING AND INITIALIZING STRING VARAIBLES

• A string variable is any valid C variable name and is always declared


as an array
– SYNTAX: char string_name[size];
• The size determines the number of characters in the string-name
– EXAMPLE: char city[10];
• When the compiler assigns a character string to a character array, it
automatically supplies a null character (‘\0’) at the end of the string.
• The size should be equal to the maximum number of characters
in the string plus one.
DECLARING AND INITIALIZING STRING VARAIBLES

• Character arrays may be initialized when they are declared


char city[9] = “NEW YORK”;
char city[9] = (‘N’,’E’,’W’,’ ‘,’Y’,’O’,’R’,’K’,’\0’);
• When we initialize a character by listing its elements, we must supply the null
terminator
• Can initialize a character array without specifying the number of elements.
DECLARING AND INITIALIZING STRING VARAIBLES

• The size of the array will be determined automatically, based on the number
of elements initialized.
char string[ ] = {'G','O','O','D','\0'};
• Can also declare the size much larger than the string size.
char str[10] = “GOOD”;
• Following will result in a compile time error.
char str[3] = “GOOD”;
• Eg:- char name[ 8] = {‘P’, ‘R’, ‘O’, ‘G’, ‘R’, ‘A’, ‘M’, '\0’};

P R O G R A M \0

1001 1002 1003 1004 1005 1006 1007 1008


DECLARING AND INITIALIZING STRING VARAIBLES

• We cannot separate the initialization from declaration


– char str[5];
– str = “GOOD”;
• Following is not allowed
– char s1[4]=”abc”;
– char s2[4];
– s2 = s1;
DECLARING AND INITIALIZING STRING VARAIBLES

• Reading words
– The input function scanf can be used with %s format specification to
read in a string of character.
char address[15];
scanf(“%s”, address);
– The problem with the scanf function is that it terminates its input on the
first white space it finds.
– A white space include blanks, tabs, carriage returns, form feeds and new
lines
INPUT: NEW YORK
– Only the string “NEW” will be read into the array address.
– In the case of character arrays, the ampersand (&) is not required before
the variable name.
– The scanf function automatically terminates the string with a null character.
EXAMPLE PROGRAM
#include<stdio.h>
int main () OUTPUT:
{
char Hello
greeting[
6] = {'H',
'e', 'l', 'l',
'o', '\0’};
//OR
// char
greeting[]
= “Hello”;
printf("Greeting message: %s\n", greeting );
return 0;
}
READING STRING FROM TERMINAL

– char line[80];
– scanf(“%s”,line);
– printf(“%s”,line);
• Will read a line of input from the keyboard and display the same on the
screen.
PRINTING STRING
PROGRAM1
main( ) OUTPUT:
{
char name[ ] = "Babbage" ; Babbage
int i = 0 ; Using puts:Babbage
while ( i <= 6 )
{
printf ( "%c", name[i] ) ;
i++ ;
}
printf(“Using puts:”);
puts(name);
}
PRINTING STRING
main( )
PROGRAM2
{ OUTPUT:
char name[ ] = "Babbage" ;
int i = 0 ; Babbage
while ( name[i]!=‘\0’ )
{
printf ( "%c", name[i] ) ;
i++ ;
}
}
EXAMPLE PROGRAM
#include <stdio.h>
main()
{
char line[100]; OUTPUT:
int i=0;
Enter Text
printf("Enter Text:\n"); String Programs
String Programs
do
{
line[i]=getchar();
i++;
} while(line[i-1] != '\n');

line[i] = '\0';
printf("\n%s\n",line);
}
READING A LINE OF
TEXT
• For reading string of text containing whitespaces is to use the library function
gets available in the <stdio.h>
gets(str)
• It reads characters into str from the keyboard until a new-line character is
encountered and then appends a null character to the string.
char line[80];
gets(line);
printf(“%s”,line);
• The last two statements may be combined
as:
printf(“%s”,gets(line));
READING A LINE OF
TEXT
• Does not check array-bounds, so do not input more characters, it may
cause problems.
• C does not provide operators that work on strings directly.
• We cannot assign one string to another directly.
string2 = “ABC”
string1 = string2;
• Are not valid.
• To copy the characters in string2 into sting1, we may do so on a character-by-
character basis.
EXAMPLE PROGRAM
#include<stdio.h>
main()
{
char string1[30], OUTPUT
string2[30]; Enter a string Str2:Europe
int i; Str1: Europe
printf("Enter a string Str2:"); Number of characters =6
scanf("%s",string2);
for(i=0;string2[i]!='\0';i++)
string1[i]=string2[i];
string1[i] = '\0';
printf("\n");
printf("Str1:%s\n",string1);
printf("Number of
characters = %d\n",i);
WRITING STRINGS TO
SCREEN
• The printf function with %s format is used to print strings to the screen.
• The format %s can be used to display an array of characters that is
terminated by the null character.
printf(“%s”, name);
• This display the entire content of the array name.
USING PUTCHAR AND
• PUTS
C supports putchar to output the values of character variables.
char ch = 'A';
putchar(ch);
• This statement is equivalent to
printf(“%c”,ch);
• Can use this function repeatedly to output string of characters stored in an
array using a loop.
char name[6] = “PARIS”;
for(i=0;i<5;i++)
putchar(name[i]);
putchar(“\n”);
USING PUTCHAR AND
PUTS
• To print the string values is to use the function puts declared in the
header file <stdio.h>
puts(str);
• str is a string variable containing a string value.
• This printf the value of the string variable str and then moves the cursor to
the beginning of the next line on the screen.
char line[80];
gets(line);
puts(line);
• Reads a line of text from the keyboard and display it on the screen.
PUTTING STRINGS
TOGETHER
• We cannot assign the string to another directly.
• We cannot join two strings together by the simple arithmetic
addition
string3 = string1 + string2; string2 = string1 + “hello”;
• The process of combining two strings together is called concatenation
COMPARISON OF TWO
STRINGS
• C does not permit the comparison of two strings directly
if(name1 == name2)
if(name == “ABC”)
are not permitted
• It is therefore necessary to compare the two strings to be tested,
character by character.
• The comparison is done until a mismatch or one of the strings terminates
into a null character, whichever occur first.
STRING-HANDLING
FUNCTIONS
• C library supports large number of string- handling functions
• Some are

FUNCTION ACTION
strlen(s1) Finds the length of the string
strcpy(s1,s2) Copies one string over another
strcat(s1,s2) Concatenates two strings
strcmp(s1,s2) Compares two strings
strchr(s1,ch) Finds a character in string
strstr(s1,s2) Finds the substring
strrev(s1) Reverse the string
String

s
There are several standard routines that work on string variables.
• Some of the string manipulation functions are,
strcpy(string1, string2); - copy string2 into string1
strcat(string1, string2); - concatenate string2 onto the end of string1
strcmp(string1,string2); - 0 if string1 is equals to string2,
< 0 if string1 is less than string2
>0 if string1 is greater than string2
strlen(string); - get the length of a string.

strrev(string); - reverse the string and result is stored in


same string.
strlen() Function
• This function counts and return the number of characters in a string
– SYNTAX:
n = strlen(string);
• Where n is the integer variable which receives the value of the length of the
string
• The counting ends at the first null character
– EXAMPLE:
Ch = “NEW YORK”;
n = strlen(ch);
printf(String Length = %d\n”, n);
– OUTPUT:
String Length = 8
Finding length of the String without using strlen()

#include <stdio.h>
int main()
{
char str[100],i;
printf("Enter a string: \n"); OUTPUT
scanf("%s",str); Enter a string:
College
// '\0' represents end of String Length of input string: 7
for(i=0; str[i]!='\0'; ++i);
printf("\nLength of input string: %d",i);

return 0;
}
Length of strings
/* Lengths of strings */
#include <stdio.h>
main()
{
char str1[] = "To be or not to be";
char str2[] = ",that is the question";
int count = 0; /* Stores the string length */
while (str1[count] != '\0') /* Increment count till we reach the string */
count++; /* terminating character. */
printf("\nThe length of the string1 is", count);
count = 0; /* Reset to zero for next string */
while (str2[count] != '\0') /* Count characters in second string */
count++;
printf("\nThe length of the string2 is", count);
}

OUTPUT:
The length of the string1 is 18
The length of the string2 is 21
strcpy()
Function
• Works almost like a string-assignment operator
– SYNTAX:
strcpy(string1, string2);
• Assigns the content of string2 to string1
– EXAMPLE:
strcpy(city, “DELHI”);
• Assign the string “DELHI” to the string variable city
strcpy(city1, city2);
• Assigns the contents of the string variable city2 to the string variable city1
Copy String Manually without using strcpy()

#include <stdio.h>
int main()
{
char s1[100], s2[100]; OUTPUT
int i; Enter string s1:
printf("Enter string s1: "); Copycat
scanf("%s",s1); String s2: Copycat
for(i=0; s1[i]!='\0'; ++i)
{
s2[i]=s1[i];
}
s2[i]='\0';
pr
intf("Stri
ng s2:
strcat() Function
• The strcat function joins two strings together
– SYNTAX:
strcat(string1, string2);
• string1 and string2 are character array
• string2 is appended to string1
• The null character at the end of the string1 is removed and string2 is placed from there
• The string2 remains unchanged
Exampl
#include <stdio.h>
e
#include <string.h>
int main () OUTPUT:

{ Enter text1
The Earth
char s1[50], s2[50];
Enter text2
puts(“Enter text1”);
is Beautiful
gets(s1);
Final destination string:
puts(“\nEnter text2”);
The Earth is Beautiful
gets(s2);
strcat(s1, s2);
printf("Final destination
string: |%s|", s1);
}
C program to concatenate two strings without using strcat()
#include<stdio.h>
void main(void)
{
char str1[25],str2[25]; OUTPUT:
int i=0,j=0;
printf("\nEnter First String:"); Enter First String: The Earth
gets(str1); Enter Second String:is Beautiful
printf("\nEnter Second
String:"); Concatenated String is: The Earthis Beautiful
gets(str2);
while(str1[i]!='\0')
i++;
while(str2[j]!='\0')
{
str1[i]=str2[j];
j++; i++;
}
str1[i]='\0';
printf("\nConcatenated
strcmp()
Function
• Compares two strings identified by the arguments and has a value 0 if they are equal.
• If they are not, it has the numeric difference between the first non-matching
characters in the strings
strcmp(string1, string2);
– EXAMPLE:
strcmp(name1, name2);
strcmp(name1, “John”);
strcmp(“Rom”, “Ram”);
strcmp(“their”, ”there”);
• The above statement will return the value of -9 which is numeric difference
between ASCII “i” and ASCII “r” is -9.
• If the value is negative the string1 is alphabetically above string2.
C program to compare two strings using strcmp
#include <stdio.h>
#include <string.h>
int main()
{ OUTPUT
char a[100], b[100]; Enter the first string
printf("Enter the first string\n"); Hello
gets(a); Enter the second string
printf("Enter the second string\n"); Hai
gets(b); Entered strings are not equal
if( strcmp(a,b) == 0 )
printf("Entered strings are equal.\n");
else
printf("Entered strings are not equal.\
n");
}
C program to compare two strings without using strcmp()
#include <string.h>
if(dif>0)
#include<conio.h> printf("%s comes after %s",str1,str2);
void main(void) else
{ {
char str1[25],str2[25]; if(dif<0)
int dif,i=0; printf("%s comes after %s",str2,str1);
else
clrscr();
printf("Both the strings are
printf("\nEnter the first String:");
same");
gets(str1);
}
printf("\nEnter the second String:");
}
gets(str2);
OUTPUT
while(str1[i]!='\0'||str2[i]!='\0')
Enter the first String: Compare
{ Enter the second String:Compare
dif=(str1[i]-str2[i]); Both the strings are same
if(dif!=0)
break;
i++;
}
COMPARISON OF TWO
STRINGS
i=0;
while(str1[i]==str2[i] && str1[i] != '\0' && str2 != '\0')
i = i+1;
if(str1[i] == '\0' && str2 == '\0')
printf("strings are equal");
else
printf("strings are not equal");
strlwr() Function
• The strlwr function converts upper case characters of string to lower case characters.
• The syntax is: strlwr(str1);
//* Program to converts input string to lower case characters */
#include <stdio.h>
#include <string.h>
main()
{
char first[80];
printf("Enter a string: ");
gets(first);
printf("Lower case of the string is %s”,strlwr(first));
}
OUTPUT:
Enter a string: LOWER
Lower case of the string is lower
SOME MORE STRING-HANDLING
FUNCTIONS
FUNCTION ACTION
strncpy(s1,s2,n) Copies up to n characters from the string s1, to
s2. In a case where the length of s2 is less than
that of n, the remainder of s1 will be padded
with null bytes.
strncat(s1,s2,n) Appends the string s2 to the end of the string
s1 up to n characters long.
strncmp(s1,s2,n) Compares at most the first n bytes of s1 and
s2.
Program using strncpy()
#include <stdio.h>
#include <string.h>

int main ()
{ OUTPUT
char src[40]; Final copied string : This is an
char dest[12];

memset(dest, '\0', sizeof(dest));


strcpy(src, "This is an example of strncpy");
strncpy(dest, src, 10);

printf("Final copied string : %s\n", dest);


return(0);
}
Program using strncat()
#include <stdio.h>
#include <string.h>

int main () OUTPUT


Final destination string : |This is destinationThis is sou|
{
char src[50], dest[50];

strcpy(src, "This is source");


strcpy(dest, "This is destination");

strncat(dest, src, 11);


printf("Final destination string : |%s|", dest);
return(0);
}
Program using strncmp()

#include <stdio.h> if(ret < 0)


#include <string.h> printf("str1 is less than str2");
else if(ret > 0)
int main () printf("str2 is less than str1");
{ else
char str1[15], str2[15]; printf("str1 is equal to str2");
int ret;
return(0);
strcpy(str1, "abcdef"); }
strcpy(str2, "ABCDEF");

ret = strncmp(str1, str2, 4); OUTPUT


str2 is less than str1
String Programs
1. Write a program to Reverse a string.
2. Write a program to print the alphabets from 'a to z' and 'A to Z' in decimal and
character form.
3. Write a program to copy one string into another and count the number of
characters copied.
4. Write a program to check whether the string entered is Palindrome or not.
5. Write a program to count the number of words in a text.
TABLE OF
STRINGS
• We use lists of character strings, such as
– List of name of students in a class
– List of name of employees in an organization
– List of places, etc
• These list can be treated as a table of strings and a two dimensional array can be
used to store the entire list.
– EXAMPLE:
student[30][15];
is a character array which can store a list of 30 names, each of length not
more than 15 characters
char city[ ][ ] = { “Chandigarh”, “Madras”, Ahmedabad” };
ARRAY OF STRINGS

• A string is a 1-D array of characters, so an array of strings is a 2-D array of


characters.
• The row index refers to a particular string, while the column index refers to a
particular character within a string.
• Definition
char identifier[NO_OF_STRINGS][MAX_NO_OF_BYTES_PER_STRING];
• Example
char name[5][31];
Initialization
char identifier[NO_OF_STRINGS][MAX_NO_OF_BYTES_PER_STRING] =
{ "initializer 1", "initializer 2", ... };
For example,
char ch_arr[3][10] = {
{'s', 'p', 'i', 'k', 'e', '\0'},
{'t', 'o', 'm','\0'},
{'j', 'e', 'r', 'r', 'y','\0'}
};
• It is important to end each 1-D array by the null character, otherwise, it will be just an array of
characters. We can't use them as strings.

• This above initialization is equivalent to:


char ch_arr[3][10] = {
"spike",
"tom",
"jerry"
};
Initialization
• The first subscript of the array i.e 3 denotes the number of strings in the array and the
second subscript denotes the maximum length of the string.
• Each character occupies 1 byte of data, so compiler 30 bytes (3*10) of memory for the
above example.
• The name of an array is a pointer to the 0th element of the array.
• Therefore, if ch_arr points to address 1000 then ch_arr + 1 will point to address 1010.

• ch_arr + 0 points to the 0th string or 0th 1-D array.


• ch_arr + 1 points to the 1st string or 1st 1-D array.
• ch_arr + 2 points to the 2nd string or 2nd 1-D array.

• In general, ch_arr + i points to the ith string or ith 1-D array.


char planets[8][] = {"Mercury", "Venus", "Earth", "Mars", "Jupiter", ”Saturn”, ”Uranus”, ”Neptune”, “Pluto”};
Input and Output

Input
To accept input for a list of 5 names, we write
char name[5][31];
for (i = 0; i < 5; i++)
scanf(" %[^\n]s", name[i]);
The space in the format string skips leading whitespace before accepting the string.

char name[5][31] = {"Harry", "Jean", "Jessica", "Irene", "Jim"};


printf("%s", name[2]);

Output
Program that initializes 3 names in an array of strings and display them on to monitor

#include<stdio.h>
#include<string.h> OUTPUT
main() Alex
{
Phillip
int i;
Collins
char names[3][10] =
{“Alex”,
“Phillip”,“Collins” };
for(i=0; i<3; i++) printf(“%s\
n”,names[i]);
}
Search a name in a given list
#include<stdio.h>
#include<string.h> if(flag==1)
int main() printf("String found\n");
{ else
char name[5][10],found[10]; printf("\nString not found");
int j,i,flag=0;
printf("Enter the names:\n"); }
for(i=0;i<5;i++)
scanf("%s",name[i]); OUTPUT
printf("Enter the name to be searched:"); Enter the names:
scanf("%s",found); Alice
for(i=0;i<5;i++) Ziya
{ Celene
if(strcmp(name[i],found)==0) Ronald
{ Bob
flag=1; break; } Enter the name to be searched:
} Ram
String not found
Sorting of strings
#include<stdio.h>
}
int main() }
{ }
int i,j,n; printf("The sorted strings are:\n");
char str[20] for(i=0;i<n;i++)
[20],temp[20]; puts(str[i]);
puts("Enter the no. of string to be sorted:"); }
scanf("%d",&n);
for(i=0;i<=n;i++)
gets(str[i]); OUTPUT
for(i=0;i<=n;i++) Enter the no. of string to be sorted:3
{ Ziya
Ronald
for(j=i+1;j<=n;j++)
Bob
{ The sorted strings are:
if(strcmp(str[i],str[j])>0) Bob
{ Ronald
strcpy(temp,str[i]); Ziya
strcpy(str[i],str[j]);
strcpy(str[j],temp);
References
• https://www.tutorialspoint.com/c_standard_library/c_function_

• slideshare.com
THANK YOU

You might also like