POP Module 4

Download as pdf or txt
Download as pdf or txt
You are on page 1of 29

Principles of Programming using C BPOPS203

Module – 4 : Strings and Pointers

Strings :

Definition:- A string constant or a string literal can be defined as a sequence of characters

enclosed in double quotes that will be treated as a single data element followed by a null
character ‘\0’

Syntax:
char string_name[size];

Where,
char is the data type of strings
string_name is a valid identifier which is the name for the string variable size indicates the length
of the string which is to be stored

Initialization of strings:

char str1[10]= “peter”;


or
char str1[10]={‘p’,‘e’,‘t’,‘e’,‘r’};
Both the initializations mentioned are same
if we directly specify the entire string at a time we use “ ”

if we specify the characters separately we should use ‘ ’, for each character and finally enclosing
all the characters within { }
The string initialized previously will be stored in memory as

Information Science and Engineering, JIT


Principles of Programming using C BPOPS203

Reading a String:
If we declare a string by writing
Char str [100];
Then str can be read by using three ways:
1. Using scanf() function
2. Using gets() function
3. Using getchar() , getch(), getche() function repeatedly

scanf() function

We do not use “&” symbol in scanf because string name itself represent the address where it is to
be stored.
%s is the format specifier used for string.

Strings can be read by using scanf() by writing:


Scanf (“%s”, str);

Although the syntax of scanf() fucntion is well known and easy to use, the main pitfall with this
function is that the function terminates as soon as it finds a blank space.

For example, if the user enters Hello World, then strr will contain only Hello. This is because the
moment a blank space is encountered, the string is terminated by the scanf() function.

gets() function
Strings can be read by using gets() by writing:
gets (str);
gets() is a simple function that overcomes the drawbacks of scanf(). The gets() function takes the
starting address oft he string which holds the input. The string inputted using gets() is
automatically terminated with a null character.

getchar() function
Strings can be read by using gets() by writing:
getchar ( );

Information Science and Engineering, JIT


Principles of Programming using C BPOPS203

Strings can also be read by calling the getchar() function repeatedly to read a sequence of single
characters (unless terminating character is entered) and simultaneoulsy storing it in a character
array.
Example:
To raead characters of string using getchar () function.

i=0;
ch = getchar();
while ( ch != ‘ \0 ‘ )
{
str [ i ] = ch;
i++;
ch = getchar();
}
str [ i ] = ‘\0‘;

Writing a String:
Strings can be displayed on screen using three ways:
1. Using printf() function
2. Using puts() function
3. Using putchar() function repeatedly

Printf ( ) function
String can be displayed using pritnf () by writing

Printf (“%s”, str);


Both printf() and scanf() functions are called as formatted input output functions.
Both gets() and puts() functions are called as unformatted input output functions.

Information Science and Engineering, JIT


Principles of Programming using C BPOPS203

puts() function
String can be displayed using puts () by writing
puts ( str );
puts ( ) is a simple function that overcomes the drawbacks of the printf( ) function.
The puts () function writes a line of output on the screen. It terminates the line with
a newline characetr ("\n").

Information Science and Engineering, JIT


Principles of Programming using C BPOPS203

putchar() function
String can be displayed using putchar () by writing
putchar( );
putchar() function is repeatedly called to display or print the sequence of single charaters.
Example:

i=0;
while ( str [i] != ‘ \0 ‘ )
{
putchar(str[i]);
i++;
}

/* C program for reading and displaying Array of strings */


#include<stdio.h>
void main()
{
char str[50][50];
int n,i;
printf(“Enter the number of names\n”);
scanf(“%d”,&n);
printf(“Enter %d names\n”,n);
for(i=0;i<n;i++)
{
scanf(“%s”,str[i] }
printf(“Entered names are \n”);
for(i=0;i<n;i++)
{
printf(“%s\n”,str[i] }
}

Information Science and Engineering, JIT


Principles of Programming using C BPOPS203

Supressing Input :
The scanf() function can be used to read a field without assigning it to any variable. This is done
by preceeding that fields format code with ‘ * ‘
For example:
Scanf ( “%d * c %d“, &hr, &min );
The time can be read as 9:05
Here the colon would be read but not assigned to anything. Therfore, assignment supression is
particulary useful when the part of what is input needs to be supressed.

Using Scanset :
Scanset is used to define a set of characters which may be read and assigned tot he corresponding
string.
Scanset is defined by placing the characters inside square brackets prefixed with a % as shown in
the example below
% [ “ aeiou “ ]

When we use the above scanset, scanf() will continue to read characters and store then into string
variable until it encounters a character that is not specified in the scanset.

Example:
#include <stdio.h>
int main ()
{
Char str [10];
Printf(“entert the string“);
Scanf(“%[aeiou]“, str);
Printf (“the string is %s“, str):

Information Science and Engineering, JIT


Principles of Programming using C BPOPS203

Return 0;
}

String Taxonomy:
We can store a string either in fixed-length format or in variable-length format

Fixed-length strings
When storing a string in a fixed length format, you need to specify an appropriate size for
the string variable. if the size is too small then you will not be able to store all the elements in the
string. On the other hand, if the string size is large, then unnecessarily memory space will be
wasted.

Variable-length strings
A beter option is to use a variable length format in which the string can be expanded or
contracted to accommodate the elements in it.
For example,

Information Science and Engineering, JIT


Principles of Programming using C BPOPS203

if you declare a string variable to store the name of a student. If a student has along name of say
20 characters, then the string can be expanded to accommodate 20 characters.
On the other hand, a student name has only 5 characters, then the string variable can be
contracted to store only 5characters. However, to use a variable-length string format you need a
technique to indicate the end of elements that are a part of the string. Thsi can be done either by
using length-controlled string or a delimiter.

Length-Controlled Strings:
In a length-controlled string you need to specify the number of characters in a string. This count
is used by the string functions to determine the actual length oft he string variable.

Delimited Strings:
In this format, the string is ended with a delimiter. The delimiter is then used to identify the end
oft he string. We can use any character such as comma, semicolon, dash, asterisk, null character,
etc.. as a delimiter of a string.

Operations On Strings:
1. Length of a string
2. Converting characters of a string into UpperCase
3. Converting characters of a string into LowerCase
4. Concatenating two strings to form a new string
5. Apending a string to another string
6. Comparing two strings
7. Reversing a string
8. Extracting a substring from left, right, middle.
9. Inserting a string in another string
10. Indexing
11. Deleting a string from the main string
12. Replacing a pattern with another pattern in a string.

• Length of a string :
Specifies the number of characters in a given string.

Information Science and Engineering, JIT


Principles of Programming using C BPOPS203

Example : Input = “Poplab“


Output = 6

/* C program to find length of the string with out using strlen function */

#include<stdio.h>

#include<string.h>

void main()
{

char str1[50];
int i,count;
printf("Enter a string\n");

scanf("%s",str1);

count=0;

for(i=0;str1[i]!='\0';i++)

count=count+1;

printf("Length of the String=%d\n",count);

• Converting characters of a string into UpperCase :


Converts lowercase characters to uppercase characters in a
given string by making use of ASCII values of characters.
If we have to convert a lower case character to upper case character, then we just need to
subtarct 32 from the ASCII value of character.

Example : Input = “poplab“


Output = “POPLAB“

*/ Program to conver the lowercase character in a given string to upper case*/


(Refer class notes or text book for the program)

Information Science and Engineering, JIT


Principles of Programming using C BPOPS203

• Converting characters of a string into LowerCase :


Converts uppercase characters to lowercase characters in a
given string by making use of ASCII values of characters.
If we have to convert a upper case character to lower case character, then we just need to
add 32 from the ASCII value of character.

Example : Input = “POPLAB“


Output = “poplab“

*/ Program to conver the uppercase character in a given string to lowercase*/


(Refer class notes or text book for the program)

• Concatenating two strings to form a new string :


If S1 and S2 are two strings, then concatination operation
produces a string which contains characters of S1 followed by the characters of S2.

Example : Input : S1 = “POP“


S2 = ‘‘LAB“
Output = “POPLAB“

/* C program to concatenate two strings without using strcat( ) function */

#include<stdio.h>

#include<string.h>

void main()
{

char str1[20],str2[20],str3[50];

int i,k;
printf("Enter String1\n");

scanf("%s",str1);

printf("Enter String2\n");

Information Science and Engineering, JIT


Principles of Programming using C BPOPS203

scanf("%s",str2);
k=0;

for(i=0;str1[i]!='\0';i++)

str3[i]=str1[i];

k=k+1; }

for(i=0;str2[i]!='\0';i++) {

str3[k]=str2[i];

k=k+1; }

str3[k]='\0';

printf("The concatenated string is=%s\n",str3); }

***** OUTPUT *****

Enter String1 Ronald


Enter String2 Weasley

The concatenated string is=RonaldWeasley

• Appending a string to another string :


Appending one string to another string involves copying the
contents oft he source string at the end of the destination string.

Example : Input : S1 = “How are you“


S2 = ‘‘Hi“
S2 = S2 + S1
Output = “Hi How are you“

*/ Program to concatinating two string in to a single string */


(Refer class notes or text book for the program)

• Comparing Two Strings :


If S1 and S2 are two strings, then comparing two strings will
give either of these results.
1. S1 and S2 are equal
2. S1>S2, when in dictionary order S1 will come after S2

Information Science and Engineering, JIT


Principles of Programming using C BPOPS203

3. S1<S2, when in dictionary order S1 precedes S2

Example : Input : S1 = “POP“


S2 = ‘‘POP“
Output = S1 and S2 are equal

/* C program to compare two strings without using strcmp( ) function */

#include<stdio.h>

#include<stdlib.h>

#include<string.h>

void main()

{
char str1[20],str2[20];

int len1,len2,i;

printf("Enter string 1\n");

scanf("%s",str1);

printf("Enter string 2\n");

scanf("%s",str2);

len1=strlen(str1);

len2=strlen(str2);

if(len1!=len2)

printf("Strings are different\n");

else

{
for(i=0;str1[i]!='\0';i++)

{
if(str1[i]!=str2[i])

Information Science and Engineering, JIT


Principles of Programming using C BPOPS203

{
printf("Strings are different\n");

exit(0);

printf("Strings are same\n");

• Reversing the given String :


To reverse a string we just need to swap first character with
the last , second character with the second last character, so on.

Example : Input = “HELLO“


Output = ‘‘OLLEH“

/* C program to reverse a string without using strrev() function */

#include<stdio.h>

#include<string.h>

void main()
{

char str1[50],str2[50];

int i,j,len;
printf("Enter String1\n");

gets(str1);

j=0; len=strlen(str1);

for(i=len-1;i>=0;i--)

str2[j]=str1[i];

j++;

Information Science and Engineering, JIT


Principles of Programming using C BPOPS203

str2[j]='\0';

printf("The reversed string = %s\n",str2);

***** OUTPUT *****

Enter String1
Expectopetronum
The reversed string = munortepotcepxE

*/ For rest of the operations listed above please refer textbook


programs (Learning programs woulb be enough fort he rest) */

Information Science and Engineering, JIT


Principles of Programming using C BPOPS203

Character Manipulation Functions :

Information Science and Engineering, JIT


Principles of Programming using C BPOPS203

String Manipulation Functions :


C supports different string handling functions to perform different operations on the strings. All
the string handling functions are stored in the header file “#include<string.h>”.
Some of the most common used built-in string manipulation functions are

• strlen() : Returns the number of character in the given string


• strcmp() : Compares two string for their similarity
• strcpy() : Copies source string into destination string variable
• strcat() : Concatenates (joins) two string into single string
• strrev() : Reverses a given string
• strupr() : Converts characters to upper case
• strlwr() : Converts characters to lower case

String Length :- The function strlen() is used to find the length of the string in terms of
number of characters in it.

SYNTAX: strlen(string_data);

/* C program to find length of the string using strlen() function */

#include<stdio.h>

#include<string.h>

void main()
{

char str1[50];
int len;
printf("Enter a string\n");

scanf("%s",str1);
len=strlen(str1);
printf("Length of the String=%d\n",len);

***** OUTPUT ***** Enter a string mangalore


Length of the String=9

String Compare:- The function strcmp() is used to compare the string data every character of one string
is compared with the corresponding position character of second string.

SYNTAX strcmp(str1,str2)

• The function returns 0 if there is complete match (str1==str2)


• Returns positive value if str1>str2

Information Science and Engineering, JIT


Principles of Programming using C BPOPS203

• Returns negative value if str1<str2

/* C program to compare two strings using strcmp( ) function */

#include<stdio.h>

#include<string.h>

void main()
{

char str1[20],str2[20];
int k;
printf("Enter string 1\n");

scanf("%s",str1);

printf("Enter string 2\n");

scanf("%s",str2);

k=strcmp(str1,str2);

if(k==0)
printf("Strings are same\n");

else
printf("Strings are different\n");

***** OUTPUT *****

Enter string 1 mite


Enter string 2 mite

Strings are same

String n Compare :-The strncmp() funtion compares the n characters of one string to another
string

SYNTAX : strncmp(string1 ,string2 , n);

/* C program to compare two strings using strncmp( ) function */

#include<stdio.h>
Information Science and Engineering, JIT
Principles of Programming using C BPOPS203

#include<string.h>

void main()
{

char str1[20],str2[20];
int k,n;
printf("Enter string 1\n");

scanf("%s",str1);

printf("Enter string 2\n");

scanf("%s",str2);

printf("Enter value for n");

scanf("%d",&n);

k=strcmp(str1,str2,n);

if(k==0)
printf("Strings are same\n");

else
printf("Strings are different\n");

***** OUTPUT *****

Enter string 1: mite


Enter string 2: mite

Enter value for n : 2

Strings are same

String Copy:- The function strcpy() copies the content from one string to another string
SYNTAX : strcpy(str2,str1);

/* C program to copy the string using strcpy function */

#include<stdio.h>

#include<string.h>

Information Science and Engineering, JIT


Principles of Programming using C BPOPS203

void main()
{

char str1[30],str2[30];
printf("Enter string1\n");

scanf("%s",str1);
strcpy(str2,str1);
printf("The copied string is = %s\n",str2);

***** OUTPUT ***** Enter string1


mite mangalore
The copied string is = mite

/* C program to copy the string without using strcpy( ) function */

#include<stdio.h>

#include<string.h>

void main()
{

char str1[30],str2[30]; int i=0;


printf("Enter string1\n");

scanf("%s",str1);

while(str1[i]!='\0')

{
str2[i]=str1[i];

i++; }

str2[i]='\0';
printf("The Original String=%s\n",str1);

printf("The Copied String=%s\n",str2);

***** OUTPUT *****


Enter string1
Mangalapuram
The Original String=Mangalapuram The Copied String=Mangalapuram

Information Science and Engineering, JIT


Principles of Programming using C BPOPS203

String n Copy :-The strncpy() funtion copies the n characters of one string to another string
SYNTAX : strncpy(dest_string,source_string,n);
Where n is an integer value which specifies the number of characters to be copied

/* C program to illustrate strncpy( ) function */

#include<stdio.h>

#include<string.h>

void main()
{

char str1[30],str2[30];

printf("Enter String1\n");

gets(str1);
printf("String 1= %s\n",str1);

strncpy(str2,str1,10);

printf("String 2= %s\n",str2);

}
***** OUTPUT *****

Enter String1 MANGALORE_INSTITUTE_OF_TECHNOLOGY


String 1= MANGALORE_INSTITUTE_OF_TECHNOLOGY , String 2= MANGALORE_

String Concatenate :- The function strcat() is used to concatenate (attach) two strings.
SYNTAX : strcat(str1,str2);

string str2 is attached to the end of string str1

/* C program to concatenate two strings using strcat function */

#include<stdio.h>

#include<string.h>

void main()
{

char str1[30],str2[30];
printf("Enter String1\n");
scanf("%s",str1);
Information Science and Engineering, JIT
Principles of Programming using C BPOPS203

printf("Enter String2\n");
scanf("%s",str2);
strcat(str1,str2);
printf("The concatenated string is=%s\n",str1);

***** OUTPUT *****

Enter String1 Harry


Enter String2 Potter

The concatenated string is=HarryPotter

String n Concatenate: - The function strncat() is used to concatenate the specified number
of characters only

SYNTAX : strncat(string1,string2,n);

Where n is an integer value which concatenates only n characters of string2 to string1

/* C program to illustrate strncat( ) function*/

#include<stdio.h>

#include<string.h>

void main()
{

char str1[30],str2[30];
printf("Enter String1 and String2\n");

scanf("%s%s",str1,str2);
strncat(str1,str2,5);
printf("The concatenated string is=%s\n",str1);

***** OUTPUT *****

Enter String1 and String2


Hermoine
Granger
The concatenated string is=HermoineGrang

Information Science and Engineering, JIT


Principles of Programming using C BPOPS203

String Reverse:- The function strrev() is used to reverse the string .


The characters from left to right in the original string are placed in the reverse order SYNTAX

strrev(str1)

/* C program to reverse a string using strrev( ) function */

#include<stdio.h>

#include<string.h>

void main()
{

char str1[30];
printf("Enter String1\n");
gets(str1);
strrev(str1);
printf("The Reversed string =%s\n",str1);

***** OUTPUT *****

Enter String1 wingardiamleviosa


The Reversed string =asoivelmaidragniw

/* C program to check if the given string is a Palindrome or not a Palindrome */

#include<stdio.h>

#include<string.h>

void main()
{

char str1[50],str2[50];
int i,j,len,x;
printf("Enter String1\n");

gets(str1);

j=0; len=strlen(str1);

for(i=len-1;i>=0;i--)

str2[j]=str1[i];
Information Science and Engineering, JIT
Principles of Programming using C BPOPS203

j++; }

str2[j]='\0';
printf("The original String =%s\n",str1);

printf("The reversed String= %s\n",str2);

x=strcmp(str1,str2);
if(x==0)

printf("%s is a palindrome\n",str1);

else

printf("%s is not a palindrome\n",str1);

***** OUTPUT *****


The original String =malayalam

The reversed String= malayalam

malayalam is a palindrome

Array of Strings/Multi dimensional Strings :-


The two dimensional array of strings is an array of one dimensional character array which consist
of strings as its individual elements.
Syntax:

char string_name[size1][size2];

where,

char is a datatype of strings


string_name is a valid identifier which is the name of the string variable size1 indicates the
number of strings in the array
size 2 indicates the maximum length of each string.

Static Initialization of strings:-


char str1[3][10]={“Thomas”,“Bob ”,“Alice”};

Array of Strings/Multi dimensional Strings :-


Information Science and Engineering, JIT
Principles of Programming using C BPOPS203

The two dimensional array of strings is an array of one dimensional character array which consist
of strings as its individual elements.
Syntax:

char string_name[size1][size2]; where,

char is a datatype of strings


string_name is a valid identifier which is the name of the string variable size1 indicates the
number of strings in the array
size 2 indicates the maximum length of each string.

Static Initialization of strings:-


char str1[3][10]={“Thomas”,“Bob ”,“Alice”};

Dynamic Initialization of Array of strings:-

/* C program for reading and displaying Array of strings */

#include<stdio.h>

void main()
{

char str[50][50];
int n,i;
printf(“Enter the number of names\n”);

scanf(“%d”,&n);
printf(“Enter %d names\n”,n);

for(i=0;i<n;i++)
{

scanf(“%s”,str[i]

printf(“Entered names are \n”);

for(i=0;i<n;i++)
{

printf(“%s\n”,str[i]

Information Science and Engineering, JIT


Principles of Programming using C BPOPS203

Pointers:
Pointer: - A pointer is a variable which holds address of another variable or a memory-location.

Advantages of Pointers:
• Pointers are more efficient in handling arrays and data tables.
• Pointers can be used to return multiple values from a function.
• Pointers allow ‘C’ to support dynamic memory management.
• Pointers provide when efficient tool for manipulating dynamic data structures such as

stack, queue etc.

• Pointers reduce length and complexity of programs.


• They increase execution speed and this reduces program execution time

Declaration and Initialization of pointers :- The operators used to represent


pointers are

• – Address Operator (&)


• – Indirection Operator (*) Syntax :-

ptr_data_type *ptr_var_name; ptr_var_name = &var_name;

– where var_name is a variable whose address is to be stored in the pointer.

Example :- int a=10;

int *ptr;

then

ptr = &a;

*ptr = a;

Here ptr is a pointer holding the address of variable ‘a’

and *ptr holds the value of the variable a.

Information Science and Engineering, JIT


Principles of Programming using C BPOPS203

#include<stdio.h>

void main()
{

int *ptr;
int x=22;
printf("Addres of x= %d\n",&x);

printf("Content of x= %d\n",x);

ptr=&x;
printf("Addres of pointer= %d\n",ptr);

printf("Content of pointer= %d\n",*ptr);

Types of Pointers:
1. Null Pointers:
We have seen that a pointer variable is a pointer to some other variable of the same
data type. However in some cases we may prefer to have null pointer which is a special
pointer that doesnot point to any value. This means that a null pointer does not point to any
valid memory address.

To declare a null pointer you may use the predefined constant NULL, which is defined in
several standard header files including : <stdio.h>,<stdlib.h>,<string.h>.

Syntax: int *ptr = NULL;

Initialization of null pointer can be done as

int ptr;

ptr = 0;

2. Generic Pointers:
A generic pointer is a pointer variable that has void as its data type. The void pointer,
or the generic pointer, is a special type of pointer that can be used to point to a variable of
any data type.

It is declared as a normal pointer variable but using the void keyword as the pointers data
type.

Information Science and Engineering, JIT


Principles of Programming using C BPOPS203

For example:

void *ptr;

Since you cannot have a variable of type void, the void pointer will therefore not point to
any data and thus cannot be dereferenced. You need to typecast a void pointer to another
kind of pointer before using it.

Information Science and Engineering, JIT


Principles of Programming using C BPOPS203

Passing arguments to function using pointers:


While using pointers to pass the arguments to a function, the calling function must pass the
addresses of the variables as arguments and the called function must dereference the arguments
to use them in the function body for processing.

Information Science and Engineering, JIT


Principles of Programming using C BPOPS203

Information Science and Engineering, JIT

You might also like