0% found this document useful (0 votes)
10 views52 pages

Strings: ©LPU CSE101 C Programming

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

Strings: ©LPU CSE101 C Programming

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

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

©LPU CSE101 C Programming


Introduction
• Use of C standard library functions: for strings
Quick yak
and characters: Discussion fo
r
g usage can
– s t rin
Easy string and character processing d
be exemplifie
– Programs can process characters, ing
mentionstrings, lines of
text, and blocks of memory• Goongslelator!!!
Tra
• These techniques are used to make
– Word processors
– Page layout software
– Typesetting programs

©LPU CSE101 C Programming


Fundamentals of characters
• Characters
– Building blocks of programs
• Every program is a sequence of meaningfully grouped
characters
– Character constant
• An int value represented as a character in single quotes
• 'z' represents the integer value of z (122 ASCII value).

©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


Fundamentals of strings
• 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 coloruhas 5 eelements
\0 b l u e \0
color Temporary

©LPU CSE101 C Programming


*colorPtr
char *colorPtr = "blue"; //pointer variable
Printf(“%s”, colorPtr);

Is correct way to use pointer to char. But:


char *colorPtr; //pointer variable
scanf(“%s”, &colorPtr);
printf(“%s”, colorPtr); /* invalid statement %s don’t
work with pointer to char */

©LPU CSE101 C Programming


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>
Program to
void main() read and
{
display string
char carname[20]; //string char array
printf(“Enter the name of your car: ");
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


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

printf(“\nString is: ”)
puts(name); //to output const string

}//end main

Enter a string:
Lovely Professional University
Output
String is:
Lovely Professional University
©LPU CSE101 C Programming
#include <stdio.h>
Program to
void main() print strings
{
character by
char name[]={“Lovely Professional character using
University"}; //string char array
int i=0; loop.
while(name[i]!='\0') //untill null character
{
printf("%c", name[i]);
i++;
}//end while

}//end main
Lovely Professional University
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
– Search strings

©LPU CSE101 C Programming


String Manipulation Functions
• List of string manipulation functions
Function prototype Function description
char *strcpy( char *s1, const char *s2 ) Copies string s2 into array s1. The value
of s1 is returned.
char *strncpy( char *s1, const char *s2, Copies at most n characters of string s2
int n ) into array s1. The value of s1 is returned.
char *strcat( char *s1, const char *s2 ) Appends string s2 to array s1. The first
character of s2 overwrites the
terminating null character of s1. The
value of s1 is returned.
char *strncat( char *s1, const char *s2, Appends at most n characters of string s2
int n ) to array s1. The first character of s2
overwrites the terminating null character
of s1. The value of s1 is returned.

©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


Example Code
This program
demonstrates
string
manipulation
/ processing
functions:
strcpy() and
strncpy()

©LPU CSE101 C Programming


Output
The string in array x is: Happy Birthday to You
The string in array y is: Happy Birthday to You
The string in array z is: Happy Birthday

©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


Example Code
This program
demonstrates
string
manipulation
/ processing
functions:
strcat() and
strncat()

©LPU CSE101 C Programming


output
s1 = Happy
s2 = New Year
strcat( s1, s2 ) = Happy New Year Quick yak:
to
strncat( s3, s1, 6 ) = Happy
Ask students
strcat( s3, s1 ) = Happy Happy New Year mes
print their na
as:
a
Ankur Sharm
r
Sharma Anku
Ankur S.
A. Sharma

©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


Example Code
This program
demonstrates
string
comparison
functions:
strcmp() and
strncmp()

©LPU CSE101 C Programming


Output
s1 = Happy New Year
s2 = Happy New Year
s3 = Happy Holidays
Quick yak:
strcmp(s1, s2) = 0 Students to
create a
strcmp(s1, s3) = 1
strcmp(s3, s1) = -1
me:
friendship ga
Based on the
strncmp(s1, s3, 6) = 0
strncmp(s1, s3, 7) = 1
strncmp(s3, s1, 7) = -1 score out of
-1,0,1 of first
o
names of tw
people….

©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


#include <stdio.h>
#include <string.h>
Program
void main() demonstrates
{
/* initialize 3 char pointers */
string length
const char *string1 = function strlen()
"abcdefghijklmnopqrstuvwxyz";
const char *string2 = "four";
const char *string3 = "Boston";
printf("%s\"%s\"%s%d\n%s\"%s\"%s%d\n%s\"%s\"%
s%d\n",
"The length of “,string1,"is",
strlen(string1),
"The length of “,string2,”is“,
strlen(string2),
"The length of “,string3,”is“,
strlen(string3));
} /* end main */

©LPU CSE101 C Programming


The length of "abcdefghijklmnopqrstuvwxyz" is 26
The length of "four" is 4
The length of "Boston" is 6
Outline
• String Conversion Functions
• Character arithmetic
• Sorting of strings.

©LPU CSE101 C Programming


String Conversion Functions
• String Conversion functions
– In <stdlib.h> (general utilities library)
• Convert strings of digits to integer and
floating-point values
Function prototype Function description
double atof( const char *nPtr ); Converts the string nPtr to double.
int atoi( const char *nPtr ); Converts the string nPtr to int.
long atol( const char *nPtr ); Converts the string nPtr to long int.
double strtod( const char *nPtr, char Converts the string nPtr to double.
**endPtr );
long strtol( const char *nPtr, char Converts the string nPtr to long.
**endPtr, int base );
unsigned long strtoul( const char Converts the string nPtr to unsigned long.
*nPtr, char **endPtr, int base );
©LPU CSE101 C Programming
atof()
Function atof
• Function atof converts its argument—a string
that represents a floating-point number—to
a double value.
• The function returns the double value.
• If the converted value cannot be
represented—for example, if the first
character of the string is a letter—the
behavior of function atof is undefined.

©LPU CSE101 C Programming


Example Code
This program
demonstrates
string
conversion
function: atof()

The string "99.0" converted to double is 99.000


The converted value divided by 2 is 49.500 output
©LPU CSE101 C Programming
atoi()
Function atoi
• Function atoi converts its argument—a string
of digits that represents an integer— to an
int value.
• The function returns the int value.
• If the converted value cannot be represented,
the behavior of function atoi is undefined.

©LPU CSE101 C Programming


Example Code
This program
demonstrates
string
conversion
function: atoi()

The string "2593" converted to int is 2593


The converted value minus 593 is 2000 output
©LPU CSE101 C Programming
atol()
Function atol
• Function atol converts its argument—a string of
digits representing a long integer— to a long
value.
• The function returns the long value.
• If the converted value cannot be represented,
the behavior of function atol is undefined.
• If int and long are both stored in 4 bytes,
function atoi and function atol work identically.

©LPU CSE101 C Programming


Example Code
This program
demonstrates
string
conversion
function: atol()

The string "1000000" converted to long int is 1000000


The converted value divided by 2 is 500000 output
©LPU CSE101 C Programming
strtol()
• Function strtol converts to long a sequence of
characters representing an integer.
• The function receives three arguments—a string
(char *), a pointer to a string and an integer.
• The string contains the character sequence to be
converted.
• The pointer is assigned the location of the first
character after the converted portion of the string.
• The integer specifies the base of the value being
converted(octal, decimal or hexadecimal format).
©LPU CSE101 C Programming
#include <stdio.h>
#include <stdlib.h> This program
int main( void )
{ demonstrates
const char *string = "-1234567abc"; /* initialize
string pointer */
string
char *remainderPtr; /* create char pointer */
long x; /* variable to hold converted sequence */
conversion
x = strtol( string, &remainderPtr, 0 ); function: strtol()
printf( "%s\"%s\"\n%s%ld\n%s\"%s\"\n%s%ld\n",
"The original string is ", string,
"The converted value is ", x,
"The remainder of the original string is ",
remainderPtr,
"The converted value plus 567 is ", x + 567 );

return 0;
} /* end

The original string is "-1234567abc"


The converted value is -1234567
The remainder of the original string is "abc"
The converted value plus 567 is -1234000

©LPU CSE101 C Programming


strstr
• Function strstr <string.h>
char *strstr(const char *s1, const char *s2);
• Function strstr searches for the first occurrence
of its second string argument in its first string
argument.
• If the second string is found in the first string, a
pointer to the location of the string in the first
string argument is returned.
• Otherwise, a NULL pointer is returned

©LPU CSE101 C Programming


#include <stdio.h>
#include <string.h> Program
int main( void ) searches for the
{
const char *string1 = "abcdefabcdef"; /* string to
first occurrence
search */
const char *string2 = "def"; /* string to search for
of string2 in
*/ string1.
printf( "%s%s \n%s%s\ n\n %s\ n %s%s\n",
"string1 = ", string1, "string2 = ", string2, "The
remainder of string1 beginning with the", "first
occurrence of string2 is:", strstr(string1, string2));

} /* end main */

string1 = abcdefabcdef
string2 = def

The remainder of string1 beginning with the


first occurrence of string2 is: defabcdef

©LPU CSE101 C Programming


Character arithmetic
• To perform increment , decrement, addition
subtraction operations on the characters.
• These operations work on the ASCII value of
characters.
• Starting from ASCII value of ‘a’ = 97 to the
ASCII value of ‘z’ = 122

©LPU CSE101 C Programming


Increment
• To display next char value
void main()
{
char x = 'a' + 1;
printf("%c", x); // Display Result = 'b‘
printf("%c", ++x); // Display Result = ‘c‘

©LPU CSE101 C Programming


Decrement
• To display previous char value
void main()
{
char x = ‘b' - 1;
printf("%c", x); // Display Result = ‘a‘
}

©LPU CSE101 C Programming


Addition
• Adding two ASCII values
void main()
{
char x = 'a‘ + ‘c’;
printf("%c", x); /* Display Result = - ( addition of
ASCII of a and c is 196) */
}

©LPU CSE101 C Programming


Subtraction
• Adding two ASCII values Quick yak:
ip
void main() The friendsh
W
{ game can NO
e
char x = ‘z’ – ‘a’; be made mor
e
comprehensiv
printf("%c",x); /* Display Result = ↓ (difference
CII
based on AS
between ASCII of z and a ) */
values of
} characters in
es
the First Nam

©LPU CSE101 C Programming


Sorting of strings
• To sort the strings in increasing order.
– That is if list of names is given then sort the list in
alphabetical order.
• Use strcmp() and strcpy() functions.

©LPU CSE101 C Programming


#include<stdio.h>
#include<conio.h>
#include<string.h>
Program to sort
main()
{ the strings
char name[20][20];
char temp[20];
int i,j,n,l;
using arrays.
printf("Enter the no. of string to be sorted");
scanf("%d",&n);
printf(“Enter %d strings:\n", n);
for(i=0;i<=n;i++)
gets(name[i]);
for(i=0;i<=n;i++)
{
for(j=i+1;j<=n;j++)
{
l = strcmp(name[i], name[j]);
if(l>0) // if first string is greater then swap
{
strcpy(temp, name[i]);
strcpy(name[i],name[j]);
strcpy(name[j],temp);
}
}
}
puts("Sorted list is:\n");
for(i=0;i<=n;i++)
puts(name[i]);
getch();
}

©LPU CSE101 C Programming


Enter the no. of string to be sorted 3
Enter 3 strings
lovely
aananya
aman preet
Sorted list is:
aananya
aman preet
lovely

©LPU CSE101 C Programming


Next Lecture

Marking the attendance of


students by passing attendance
sheet …??
Pointer
©LPU CSE101 C Programming
[email protected]

You might also like