You are on page 1of 24

UNIT III

STRINGS & POINTERS

9-1
Contents

• Strings: Declaring and defining a string,


Initialization of strings, Strings Library
functions.
• Pointers: Fundamentals of pointer, Pointer
Declarations, Parameter passing: Pass by value,
Pass by reference, Dynamic memory allocation.

Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 9-2


Strings

9-3
Contents

• Declaring and defining a string


• Initialization of strings
• Strings library functions

Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 9-4


Definition and Declaration

• Strings are defined as an array of characters. The


difference between a character array and a string
is the string is terminated with a special
character ‘\0’.
• Declaration of strings: Declaring a string is as
simple as declaring a one dimensional array.
Below is the basic syntax for declaring a string.
• char str_name[size];

Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 9-5


Strings
• C implements the string data structure using
arrays of type char.
• Since string is an array, the declaration of a
string is the same as declaring a char array.
– char string_var[30];
– char string_var[20] = “Initial value”;

9-6
Memory Storage for a String

• The string is always ended with a null character


‘\0’.
• The characters after the null character are
ignored.
• e.g., char str[20] = “Initial value”;
[0] [13]
I n i t i a l v a l u e \0 ? ? …

Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 9-7


Initializing a String
• A string can be initialized in different ways. We
will explain this with the help of an example.
Below is an example to declare a string with
name as str and initialize it with “Geeks”.
• 1. char str[] = "Geeks";
• 2. char str[50] = "Geeks";
• 3. char str[] = {'G','e','e','k','s','\0'};
• 4. char str[14] = {'G','e','e','k','s‘,'\0‘};

9-8
Example 1:declare and initialize string
#include<stdio.h>
int main()
{
// declare and initialize string
char str[] = ”Program";
// print string
printf("%s",str);
return 0;
}

Output:
Program

Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 9-9


Input/Output of a String
• The placeholder %s is used to represent string
arguments in printf and scanf.
– printf(“Topic: %s\n”, string_var);
• The string can be right-justified by placing a
positive number in the placeholder.
– printf(“%8s”, str);
• The string can be left-justified by placing a
negative number in the placeholder.
– Printf(“%-8s”, str);

Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 9-10


Example 2:C program to read strings
#include<stdio.h>
int main()
{
// declaring string
char str[50];
// reading string
scanf("%s",str);
// print string
printf("%s",str);
return 0;
}

9-11
Arrays of Strings

• An array of strings is a two-dimensional array of


characters in which each row is one string.
– char names[People][Length];
– char month[5][10] = {“January”,
“February”, “March”, “April”,
“May”};

Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 9-12


Right and Left Justification of
Strings
The “%8s” placeholder displays a string which is right-
justified and in 8-columns width.
If the actual string is longer than the width, the displayed field
is expanded with no padding.

Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 9-13


Example Programs
1.C program to read and print a string.
2.C program to print a string using loop.
3. C program to print the 5 different subject names.
4.C program to print the number of characters in a string.
5.C program to count the number of capital and small
letters in a string.
6.C Program to Count the Number of Vowels, Consonants
,digits and spaces.

Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 9-14


String Library Functions

• The string can not be copied by the assignment


operator ‘=’.
– e..g, “str = “Test String”” is not valid.
• C provides string manipulating functions in the
“string.h” library.

Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 9-15


Some String Functions from String.h
Function Purpose Example
strcpy Makes a copy of a strcpy(s1, “Hi”);
string
strcat Appends a string to the strcat(s1, “more”);
end of another string
strcmp Compare two strings strcmp(s1, “Hu”);
alphabetically
strlen Returns the number of strlen(“Hi”)
characters in a string returns 2.
strtok Breaks a string into strtok(“Hi, Chao”,
tokens by delimiters. “ ,”);
Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 9-16
Functions strcpy and strncpy
• Function strcpy copies the string in the second
argument into the first argument.
– e.g., strcpy(dest, “test string”);
– The null character is appended at the end automatically.
– If source string is longer than the destination string, the
overflow characters may occupy the memory space used by
other variables.
• Function strncpy copies the string by specifying the
number of characters to copy.
– You have to place the null character manually.
– e.g., strncpy(dest, “test string”, 6); dest[6] = ‘\0’;
– If source string is longer than the destination string, the
overflow characters are discarded automatically.
Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 9-17
Extracting Substring of a String (1/2)
• We can use strncpy to extract substring of one string.
– e.g., strncpy(result, s1, 9);

Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 9-18


Distinction Between Characters and
Strings
• The representation of a char (e.g., ‘Q’) and a
string (e.g., “Q”) is essentially different.
– A string is an array of characters ended with the null
character.

Q Q \0

Character ‘Q’ String “Q”

Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 9-19


String Comparison (1/2)
• Suppose there are two strings, str1 and str2.
– The condition str1 < str2 compare the initial memory
address of str1 and of str2.
• The comparison between two strings is done by
comparing each corresponding character in them.
– The characters are comapared against the ASCII table.
– “thrill” < “throw” since ‘i’ < ‘o’;
– “joy” < joyous“;
• The standard string comparison uses the strcmp and
strncmp functions.

Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 9-20


String Comparison (2/2)
Relationship Returned Value Example
str1 < str2 Negative “Hello”< “Hi”
str1 = str2 0 “Hi” = “Hi”
str1 > str2 Positive “Hi” > “Hello”

• e.g., we can check if two strings are the same by


if(strcmp(str1, str2) != 0)
printf(“The two strings are different!”);

Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 9-21


.

#include <stdio.h>
#include <string.h>
int main () {
char str1[12] = "Hello";
char str2[12] = "World";
char str3[12];
int len ;
/* copy str1 into str3 */
strcpy(str3, str1);
printf("strcpy( str3, str1) : %s\n", str3 );
/* concatenates str1 and str2 */
strcat( str1, str2);
printf("strcat( str1, str2): %s\n", str1 );

/* total lenghth of str1 after concatenation */


len = strlen(str1);
printf("strlen(str1) : %d\n", len );

return 0;
} 9-22
Output:

strcpy( str3, str1) : Hello


strcat( str1, str2): HelloWorld
strlen(str1) : 10

Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 9-23


Lab Syllabus

a) Write a program in C to find the frequency of characters in a


string.
b) Write a C program to implement all string operations (string
length, string copy, string compare, string concatenation and
string reverse) without using string library functions.

Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 9-24

You might also like