String Manipulation Functions-Introduction To Programming-Lecture Notes, Study notes of Computer Programming

A program is a precise sequence of steps to solve a particular problem. This course includes basic programming structure like loops, operator, memory allocation, reference, pointers etc. It teaches how to be a good programmer. This lecture handout is about: String, Manipulation, Function, Character, Handling, Conversion, Search, Sample, Program, Word, Processor, UNIX, ASCII, Codes, Memory

Typology: Study notes

2011/2012

Uploaded on 08/06/2012

anchal
anchal 🇮🇳

4.6

(9)

95 documents

1 / 12

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
186
1
Reading Material
Lecture No. 7
Deitel & Deitel - C
30, 5.31, 5.32,
16.33 ( Pages 869 –
884)
,
g may be handled. Before actually discussing the subject, it is
ertinent to know how the things were going on before the evolution of the concept of
ere being developed in BELL
aboratories, the scientists wanted to publish the articles. They needed a text editor to
hat they needed was some easy mechanism by which the
matted and published. We are talking about the times when PCs
did not exist. It may be very strange thing for you people who
an perform the tasks like making the characters bold, large or format a paragraph
++ How to Program Chapter 5
5.29,5.
5.33, 5.34
Chapter 16
16.16
Summary
x String Handling
x String Manipulation Functions
x Character Handling Functions
x Sample Program
x String Conversion Functions
x String Functions
x Search Functions
x Examples
x Exercises
String Handling
We have briefly talked about 'Strings' in some of the previous lectures. In this lecture
you will see how a strin
p
'strings'.
When C language and UNIX operating system w
L
publish the articles. W
articles could be for
and word processors
c
docsity.com
pf3
pf4
pf5
pf8
pf9
pfa

Partial preview of the text

Download String Manipulation Functions-Introduction To Programming-Lecture Notes and more Study notes Computer Programming in PDF only on Docsity!

Reading Material

Lecture No. 7

Deitel & Deitel - C

16.33 ( Pages 869 –

g may be handled. Before actually discussing the subject, it is ertinent to know how the things were going on before the evolution of the concept of

ere being developed in BELL aboratories, the scientists wanted to publish the articles. They needed a text editor to hat they needed was some easy mechanism by which the matted and published. We are talking about the times when PCs did not exist. It may be very strange thing for you people who an perform the tasks like making the characters bold, large or format a paragraph

++ How to Program Chapter 5

Chapter 16

Summary

 String Handling  String Manipulation Functions  Character Handling Functions  Sample Program  String Conversion Functions  String Functions  Search Functions  Examples  Exercises

String Handling

We have briefly talked about 'Strings' in some of the previous lectures. In this lecture you will see how a strin p 'strings'. When C language and UNIX operating system w L publish the articles. W articles could be for and word processors c

docsity.com

help of word processors these days. Those scientists had not such a facility ailable with them. The task of writing article and turning into publishable material as ma e with the help of typewriters. Then these computer experts decided to t editing in an easy anner. The resultant efforts led to the development of a program for editing the text. ands were itten as a part of the text and were processed on out put. Later, such programs were olved erted for the functions like making the character

. The effect of this command could be preview and then modified if needed. s again, we will discuss in detail the in-built nctio to handle the strings.

in Ma ctions

ctions to manipulate strings. To understand the io s, let’s lock (or unit) of a string i.e., a character. Characters ted rs in terms of numbers. There is a code number for computer. Mostly the computers use ASCII (American ation Interchange) code for a character to store it. This is r memory for manipulation. It is used as an output in the form of ct r. We can write a program to see the ASCII values. av dat type c ore a character. A character includes every thing, which can a, full stop and colon etc numbers, they are treated her data type is called as int , which rs are stored in side computer as m. A character is stored in the ns that 2^8 (256) different combinations for to ascertain what number it stores, when we we will see what character will be displayed emory. e code of the program, which displays the characters and their corresponding teger, values (ASCII codes) as under. n the program the statement c = i ; has integer value on right hand side (as i is an int) lay the value of i and c. It shows us

the ASCII code table

iostream.h>

int i, char c ; for (i = 0 ; i < 256 ; i ++)

cout << i << “\t” << c << “\n” ;

with the av w inly don develop a program, which could help in the processing of tex m The process to edit text was called text processing. The in- line comm wr ev in which a command was ins bold Now coming to the topic of string fu ns

Str g nipulation Fun

C language provides many fun fun ct n consider building b are represen inside the compute each character, used by a Standard Code for Inform used in the compute chara e We h e a a har to st we type with a keyboard for example white space, comm all are characters. 0, 1, 2 arealso characters. Though, as differently, yet they are typed as characters. Anot stores whole numbers. As we know that characte numbers so these can be manipulated in the same for memory in one byte i.e. 8 bits. It mea different values can be stored. We want press a key on the board. Inother words, when we have a number in m Th in I while c has its character representation. We disp the characters and their integer values.

//This program displays

include <

main ( ) {

c = i ;

docsity.com

int isspac R e ( '\n' ), space ( ' ' ), form feed ( '\f' ), carriage return ( '\r' ), horizontal tab ( '\t' ), or vertical tab ( '\v' )—and false otherwise

e( int c ) eturns true if c is a white-space character—newlin

i nt iscntrl( int c ) Returns true if c is acontrol character and false otherwise.

int ispunct( int c ) Returns true if c is a printing character other than a space, a digit, or a letter and false otherwise.

i s true value if c is a printing character including space ( ' ' ) and false otherwise.

nt isprint( int c ) Return

i rns true if c is a printing character other than space ( ' ' ) and otherwise.

nt isgraph( int c ) Retu false

The functions tolower and toupper are conversion functions. The tolower function converts its uppercase letter argument into a lowercase letter. If its argument is other than uppercase letter, it returns the argument unchanged. Similarly the toupper function converts its lowercase letter argument into uppercase letter. If its argument is other than lowercase letter, it returns the argument without effecting any change.

Let’s consider the following example to further demonstrate the use of the functions whi Then the string entered is checked to count different types of characters (digit, upper e ke d in different types will be displayed. In this exam using a function getchar() , tion is While carrying out character manipulation, w is function reads a single character from the input buffer or keyboard. This function can get the new line character ‘\n’ (the ENTER key) so we run the loop for input until the g (i.e. new line character ‘\n’), the loop is termi t returns a value. When we use an assignment s getchar()) , the value assigned to the left hand a to char c. Afterwards, this value is compared wit equal inside the loop, we apply the tests on c t ter,

Following is the code of this program. using l

#include include

S ample Program

of ctype.h. Suppose, we write a program ch prompts the user to enter a string.

and lowercase letters, white space etc). W character entered. When the user ends the inp

ep a counter for each category of ut, the number of characters entere ple we are instead of cin to get the input. This func defined in header file as stdio.h. e use the getchar() function. Th

user presses the ENTER key. As soon as etchar() gets the ENTER key pressed nated. We know that, every C statemen tatement ( as used in our program c = side variable is the value of the statement too. Thus, the statement (c = getch r()) returns the value that is assigned h the new line character ‘\n’. If it is not o check whether it is uppercase let lowercase letter or a digit etc. In this program manipulated character.

, the whole string entered by the user is

// Example: analysis of text ibrary

#include

docsity.com

ain()

lc++;

out << "You typed:"<< endl; wer case letters = "<< lc<< endl; pper case letters = " << uc < cout << "\n OK, you have entered " << anInteger; } }

The output of the program is as follows.

Enter an integer between 10-100 : 45. OK, you have entered 45

String Functions

We know a program to guess a number, stored in the computer. To find out a name (which is a character array) among many names in the memory, we can perform string comparison on two strings by comparing a character of first string with the length py a

heir description. All

corresponding character of the second string. Before doing this, we check the of both the strings to compare. C library provides functions to compare strings, co string and for other string manipulations. The following table shows the string manipulation functions and t these functions are defined in the header file string.h , in the C library.

Function prototype Function description

*ch st char s2 ) Copies string^ s2^ into character array^ s. The value of is returned.

**ar *strcpy( char *s1, con s ch ar *strncpy( char s1, const char s2, 2 size_t n )

Copies at most n characters of string s into array s1. The value of s1 is returned. ch t

inating null character of s1. The value of is returned.

**ar *strcat( char s1, const char s2 ) Appends string s2 to array s1. The firs character of s2 overwrites the term **s c har *strncat( char s1, cons t char s2, Appends at most n characters of string s size_t n ) to array s1. The first character of s overwrites the terminating null character of s1. The value of s1 is returned. *int strcmp( const char s1, const ch =

*ar s2) Compares string s1 to s2. Returns a negative number if s1 < s2 , zero if s1 = s2 or a positive number if *s1 > s int strncmp( const char s1, const c size_t n )

*har s2, Compares up to n characters of string to s2. Returns a negative number if s1 < s2 , zero if s1 == s2 or a positive number if s1 > s2.

s

*int strlen ( const char s) Determines the length of string s. The number of characters preceding the terminating null character is returned.

Let’s look at the string copy function which is strcpy. The prototype of this function is

docsity.com

**char strcpy( char s1, con

gument is a pointer to a st pointer to that resultant string is retu

keyword is used before the na any change in the source string (i.e. a string instead of the entire string, strncpy has arguments a pointer to g (s2). The third argument is int n. H to copy from s2 into s1. Here s1 mu characters. he next function is strcat (string concatenation). This function concatenates (joins) r example, in a string, we have first name of a student, followed by

*ar strcat( the end of of s1 are not overwritten. We can f characters of s2 to s1 by using the function strncat. Here we three arguments, a character pointer to s1, a character pointer to ent is the number of characters to be concatenated. The prototype unction is written as **char *strncat( char s1, const char s2, size_t n )

onstrate the use of strcpy, strncpy, ns. To begin with, we can fully understand the use of the .

ogram to display the operation of the strcpy() and strncpy()

id m

har string1[15]="String1";

ut<<"Before the copy :"<

include

vo ain() { c char string2[15]="String2";

co cout<<"String 1:\t"< Now we come across the function strcmp. This function compares two strings, and depending upon the result of the comparison. The prototype **int strcmp( const char s1, const char s2) s a number less than zero (a negative number), if s1 is less than s1 and s2 are identical and returns a positive number (greater than ara ter in string and lower and upper case

re not identical. sed to compare a number of ings. The prototype of this function is **const char s1, const char s2, size_t n ) gs and n is the number upto which the characters of s s also int. It returns a negative number if first n haracters of s2. It returns zero if n characters of entical. However, it returns a positive number if n greater than n characters of s2. e will talk about the function, ‘ strlen’ (string length) which is used to

ith

ng.

returns an integer value of this function is This function return s2. It returns zero if zero) if s1 is greater than s2. The space ch c a letters are also considered while comparing two strings. So the strings “Hello”, “hello” and “He llo” are three different strings these a Similarly there is a function strncmp , which can be u characters of two str int strncmp( Here s1 and s2 are two str in and s2 are compared. Its return type i characters of s1 are less than first n c s1 and n characters of s2 are id characters of s1 are Now w determine the length of a character string. This function returns the length of the string passed to it. The prototype of this function is given below. *int strlen ( const char s) This function determines the length of string s. the number of characters preceding the terminating null character is returned.

Search Functions

C provides another set of functions relating to strings, called search functions. W the help of these functions, we can do different types of search in a string. For example, we can find at what position a specific character exists. We can search a character starting from any position in the string. We can find the preceding or proceeding string from a specific position. We can find a string inside another stri These functions are given in the following table.

Function prototype Function description

**c har strchr( const char s, int c ); Locates the first occurrence of character c in string s. If c is found, a pointer to c in s is returned. Otherwise, a NULL pointer is returned. s co

**ize_t strcspn( const char s1, nst char s2 );

Determines and returns the length of the initial segment of string s1 consisting of characters not contained in string s. s ch

*ize_t strspn( const char s1, const l *ar s2 );

Determines and returns the length of the initia segment of string s1 consisting only of characters contained in string s. c co s2 is

rned.

**har *strpbrk( const char s1, nst char s2 );

Locates the first occurrence in string s1 of any character in string s2. If a character from string found, a pointer to the character in string s1 is returned. Otherwise, a NULL pointer is retu c );

**har strrchr( const char s, int c Locates the last occurrence of c in string s. If c is found, a pointer to c in string s is returned.

docsity.com

Otherwise, a NULL pointer is returned. c ch

**har strstr( const char s1, const. *ar s2 );

Locates the first occurrence in string s1 of string s If the string is found, a pointer to the string in s1 is returned. Otherwise, a NULL pointer is returned. *c s

o

. and

**har strtok( char s1, const char 2 );

A sequence of calls to strtok breaks string s1 int “tokens”—logical pieces such as words in a line of text—separated by characters contained in string s The first call contains s1 as the first argument, subsequent calls to continue tokenizing the same string contain NULL as the first argument. A pointer to the current token is returned by each call If there are no more tokens when the function is called, NULL is returned.

Example 3 Here is an example, which shows the use of different string manipulation functions.

g.h> .h>

ity); );

The code of the program is given below. //A program which shows string manipulation using library

#include #include