Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
197 views

Lecture-14-String Handling Functions PDF

The document discusses string handling functions in C including strlen(), strcpy(), strcat(), strcmp(), and substr(). It provides the definitions and examples of using each function. For example, it explains that strlen() returns the length of a string, strcpy() copies one string to another, and strcat() concatenates two strings. It also discusses implementing string operations like concatenation, comparison, and copying without using the library functions.

Uploaded by

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

Lecture-14-String Handling Functions PDF

The document discusses string handling functions in C including strlen(), strcpy(), strcat(), strcmp(), and substr(). It provides the definitions and examples of using each function. For example, it explains that strlen() returns the length of a string, strcpy() copies one string to another, and strcat() concatenates two strings. It also discusses implementing string operations like concatenation, comparison, and copying without using the library functions.

Uploaded by

Anirudha Krishna
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

Lecture-14 Character Arrays and Strings Unit-3

STRINGS

In this chapter we are going to learn the following topics:

 String Handling functions

 String Handling functions:

 C library supports a large number of string functions. The list given below depicts
the string functions
String Function Action

strlen(str) Returns length of the string str

strcpy(dest, src) Copies the source string src to destination string dest
strncpy(dest, src, n) Copies at most n characters of the source string src to
destination string dest

strcat(str1, str2) Append string str2 to string str1

strncat(str1, str2, n) Append first n characters of string str2 to string str1

strcmp(str1, str2) Compares two string str1 and str2


Returns a pointer to the first occurrence of str2 in str1, or
strstr(str1, str2) a null pointer if str2 is not part of str1

strtok(str, delim) It splits the given string wherever delimiter occurs

1
Lecture-14 Character Arrays and Strings Unit-3

 Displaying substring of given string:

substr() works with 0, 1 or 2 parameters as both parameters have defaults. The equivalent of the
Basic string functions Left(), Mid() and Right() are

String functions Actions

Left(string,len)- substr(0,len) It takes specified length of characters from left


side of the given string

Mid(string,startpos,len) - substr(startpos,len) It takes the characters from specified position


of the given string based on length of the
characters

Right(string,len) - substr( size()-startpos+1, It takes specified length of characters from


len) right side of the given string

 Left(string,len) - substr(0,len)

Ex: Left(str, 7): It displays 7 characters from the left side of the given string.

 Mid(string,startpos,len) - substr(startpos,len)

Ex: Mid(str, 5, 7): It takes the characters from specified position i.e 5 of the given string
and displays 7 characters (towards right side of the string).

 Right(string,len) - substr( size()-startpos+1, len)

Ex: Right(str, 7): It displays 7 characters from the right side of the given string.

 String Concatenation :strcat() function:


The strcat function joins two strings together. The general form is

strcat(string1,string2);

string1 and string2 are character arrays. When the function strcat is executed. String2 is
appended to string1. It does so by removing the null character at the end of string1 and
placing string2 from there. The string at string2 remains unchanged.

2
Lecture-14 Character Arrays and Strings Unit-3

Example:

Text1= VERY \0

Text2= GOOD\0

Text3= BAD\0

1. strcat(text1,text2);

Text1= VERY GOOD\0

Text2= GOOD\0

2. strcat(text1,text3);
Text1= VERY BAD

Text2= BAD

We must make sure that the size of string1 is large enough to accommodate the final
string. Strcat function may also append a string constant to string variable.

For example:

strcat(text1,”GOOD”);

C permits nesting of strcat functions. The statement

strcat(strcat(string1,string2),string3);

Is allowed and concatenates all the three strings together. The resultant string is stored in
string1.

 String comparison/strcmp() function:


The strcmp function compares two strings identified by the arguments and has a value 0
if they are equal.

The general form is :

strcmp(string1,string2);

String1 and string2 may be string variables or string constants.

3
Lecture-14 Character Arrays and Strings Unit-3

Examples are:

strcmp(name1,name2);

strcmp(name1, “ABHI”);

strcmp(“ROM”, “RAM”);

We have to determine whether the strings are equal, if not which is alphabetically above.

More examples:

strcmp(“yello”, “hello”) : Here strings are not equal and the letter y is greater than the
letter h, therefore the function return the value > 0.

strcmp(“hello”,“yello”): Here strings are not equal and the letter h is smaller than the
letter y, therefore the function return the value < 0.

strcmp(“hi”,“hi”): Here strings are equal and therefore the function return the value 0.

strcmpi(“Hi”,“hi”): Here strings are equal because which ignores the case sensitive
characters and therefore the function return the value 0.

 String copying/strcpy() function:


The strcpy() function works almost like a string-assignment operator.

The general format is

strcpy(string1,string2);

It copies the contents of string2 to string1. string2 may be a character variable or a string
constant.

For example, the statement

strcpy(city , “BANGALORE”);

Will assign the string “BANGALORE” to the string variable city.

4
Lecture-14 Character Arrays and Strings Unit-3

The statement strcpy(city1,city2); will assign the contents of the string variable city2 to
the string variable city1. The size of the array city1 should be large enough to receive the
contents of city2.

 Finding the length of a string/strlen();

This function counts and returns the number of characters in a string.

The general syntax is n=strlen(string);

Where n is an integer variable which receives the value of the length of the string. The
argument may be a string constant. The counting ends at the first null character.

Implementing the above functions without using string functions:

 String concatenation:
We cannot assign one string to another directly; we cannot join two strings together by
the simple arithmetic addition. The characters from string1 and string2 should be copied
into the string3 one after the other. The size of the array string3 should be large enough to
hold the total characters.

Program to show concatenation of strings:


#include<stdio.h>
main()
{
int i,j,k;
static char first_name={“ATAL”};
static char sec_name={“RAM”};
static char last_name={“KRISHNA”};
char name[30];
for(i=0;first_name[i]!=‟\0‟;i++)
name[i]=first_name;
for(i=0;second_name[j]!=‟\0‟; j++)
name[i+j+1]=sec_name[j];
name[i+j+1] =‟ „;
for(k=0;last_name[k]!=‟\0‟;k++)
name[i+j+k+2]=last_name[k];
name[i+j+k+2]=‟\0‟;
printf(“\n \n”);
printf(“%s \n”, name);
}

5
Lecture-14 Character Arrays and Strings Unit-3

Output
ATAL RAM KRISHNA

 String comparison:
Comparison of two strings cannot be compared directly. It is therefore necessary to
compare the strings to be tested, character by character. The comparison is done until
there is a mismatch or one of the strings terminates into a null character.

The following segment of a program illustrates this,

Program to show comparison between two strings:


#include<stdio.h>
main ()
{
char str1[10], str2[10];
int i;
printf(“Read first string”);
scanf(“%s”, str1);
printf(“Read second string”);
scanf(“%s”, str2);
i=0;
while(str1[i]==str2[i] && str1[i]!=‟\0‟ && str2[i]!=‟\0‟)
{
i=i+1;
if(str1[i]==‟\0‟ && str2[i]==‟\0‟)
printf(“strings are equal\n”);
else
printf(“strings are not equal\n”);
}
}

6
Lecture-14 Character Arrays and Strings Unit-3

 String copying:
strcpy(dest, src): If ‘dest’ and ‘src’ contains same string, then if we want to copy the
string from source „src‟ to the destination „dest‟ while coping it overlaps the contents then
the results are unpredictable or it displays the garbage value.
Program to show copying of two strings:
#include<stdio.h>
main()
{
char string1[80],string2[80];
int j;
printf(“Enter a string\n”);
printf(“?”);
scanf(“%s”, string2);
for(j=0;string2[i]!=‟\0‟;j++)
string1[j]=string2[j];
string1[j]=‟\0‟;
printf(“\n”);
printf(“%s\n”,string1);
printf(“Number of characters=%d\n”, j);
}

Program to find the length of a string:


#include<stdio.h>
main()
{
char line[80],character
int c=0,i;
printf(“Enter the text\n”);
for(i=0;line[i];!=‟\0‟;i++)
{
character=getchar();
line[i]=character;
c++;
}
printf(“The length of the string \n”, c);
}

7
Lecture-14 Character Arrays and Strings Unit-3

 Arithmetic operations on characters:


We can manipulate characters the same way we do with numbers. Whenever a character
constant or character variable is used in an expression, it is automatically converted into
an integer value by the system. The integer value depends on the local character set of the
system.

To write a character in its integer representation, we may write it as an integer.

For example:

y=‟a‟;

printf(“%d\n”, y);

will display the number 97 on the screen.

It is also possible to perform arithmetic operations on the character constants and


variables.

For example:

y=‟z‟-1;

Is a valid statement. In ASCII , the value of „z‟ is 122 and therefore , the statement will
assign the value 121 to the variable Y.

We may also use character constants in relational expressions.

For example:

ch>=‟a‟ && ch<=‟z‟

Would test whether the character contained in the variable ch is an lower-case letter.

We can convert a character digit to its equivalent integer value using the following
relationship:

y=character –„0‟;

Where y is defined as an integer variable and character contains the character digit.

For example: Let us assume that the character contains the digit „7‟, then,

y=ASCII value of „7‟-ASCII value of „0‟

= 55-48

=7

8
Lecture-14 Character Arrays and Strings Unit-3

C library has a function that converts a string of digits into their integer values. The
function takes the form

y=atoi(string);

y is an integer variable and string is a character array containing a string or digits

For example:

num=”1974”

year=atoi(num);

Num is a string variable which is assigned the string constant “1974”. The function atoi
converts the string “1974” to its numeric equivalent 1974 and assigns it to the integer
variable year.

 What is the difference between a string copy (strcpy) and a memory copy (memcpy)?
When should each be used?

The strcpy() function is designed to work exclusively with strings. It copies each byte of
the source string to the destination string and stops when the terminating null character
(\0) has been moved. On the other hand, the memcpy() function is designed to work with
any type of data.

Because not all data ends with a null character, you must provide the memcpy() function
with the number of bytes you want to copy from the source to the destination.

 How can I convert a number to a string?

The standard C library provides several functions for converting numbers of all formats
(integers, longs, floats, and so on) to strings and vice versa. One of these functions, itoa(),
is used here to illustrate how an integer is converted to a string:

#include <stdio.h>
#include <stdlib.h>
void main(void);
void main(void)
{
int num = 100;
char str[25];
itoa(num, str, 10);
printf("The number 'num' is %d and the string 'str' is %s.\n", num, str);
}

9
Lecture-14 Character Arrays and Strings Unit-3

Explanation: Here that the itoa() function takes three arguments: the first argument is
the number you want to convert to the string, the second is the destination string to put
the converted number into, and the third is the base, or radix, to be used when
converting the number. But this example uses the common base 10 to convert the
number to the string.

The following functions can be used to convert integers to strings:

Function name Purpose

itoa( ) - Converts an integer value to string

Itoa( ) - Converts a long integer value to string

utoa( ) - Converts an unsigned long integer value to string

strtoul() - Converts string to unsigned long integer

Note: the itoa(), ltoa(), and ultoa() functions are not ANSI compatible.

ASCII values for the alphabets: A to Z : 65 to 90 and

a to z : 97 to 122

10

You might also like