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

C H A R A C T E R A R R AYS

- STRINGS
Strings
Definition
 A string is an array of characters.
 Any group of characters (except double quote sign) defined
between double quotation marks is a constant string.
 Character strings are often used to build meaningful and
readable programs.
The common operations performed on strings are
 Reading and writing strings
 Combining strings together
 Copying one string to another
 Comparing strings to another
 Extracting a portion of a string ..etc.

7/16/2015 Department of CSE 2


Strings
Declaration and initialization
char string_name[size];
The size determines the number of characters in the string_name.

For example, consider the following array:


char name [20];
is an array that can store up to 20 elements of type char.
It can be represented as:

7/16/2015 Department of CSE 3


Strings
 In the above array name, we can store sequences of characters up
to 20 characters long.

 But we can also store shorter sequences.

For example,
An array name could store at some point in a program either the
sequence "Hello" or the sequence "Merry Christmas", since both
are shorter than 20 characters.

7/16/2015 Department of CSE 4


Strings
 The character sequences "Hello" and "Merry Christmas"
represented in an array name as follows :

7/16/2015 Department of CSE 5


Initialization of null-terminated
character sequences
 arrays of characters or strings are ordinary arrays
that follow the same rules of arrays.
For example
If we want to initialize an array of characters with
some predetermined sequence of characters we can
just do it like any other array:
char myWord[ ] = { 'H', 'e', 'l', 'l', 'o', '\0' };

7/16/2015 Department of CSE 6


Initialization of null-terminated
character sequences
 arrays of char elements have an additional method to
initialize their values: using string literals

 “Manipal ” is a constant string literal.


For example,
char result[14] =“Manipal”

 Double quoted (") strings are literal constants whose type is


in fact a null-terminated array of characters.

 So string literals enclosed between double quotes always


have a null character ('\0') automatically appended at the
end.
7/16/2015 Department of CSE 7
Initialization
 we can initialize the array of char elements called myWord
with a null-terminated sequence of characters by either one
of these two methods:
char myWord [ ] = { 'H', 'e', 'l', 'l', 'o', '\0' };
char myWord [ ] = "Hello";

 In both cases the array of characters myword is declared with


a size of 6 elements of type char:
 The 5 characters that compose the word "Hello" plus a final
null character ('\0') which specifies the end of the
sequence and that,
 In the second case, when using double quotes (") null
character ('\0') is appended automatically.

7/16/2015 Department of CSE 8


Example
#include <iostream.h>
void main ()
{
char question[] = "Please, enter your first name: ";
char greeting[] = "Hello, ";
char yourname [80];
cout << question;
cin >> yourname;
cout << greeting << yourname << "!";
getch();
}

7/16/2015 Department of CSE 9


Example
//include necessary header files.
void main()
{
const int MAX = 80; //max characters in string
char str[MAX]; //string variable str
cout << “Enter a string: ”;
cin >> str; //put string in str
cout << “You entered: ” << str << endl; //display string from str

7/16/2015 Department of CSE 10


Reading Embedded Blanks

To read text containing blanks we use function,


i.e
cin.get(array_name, size)
The first argument to cin.get() is the array address (array
name) where the string being input will be placed.
The second argument specifies the maximum size of the array,
thus automatically avoiding buffer overrun.
or
Also we use
gets(string)
to read everything that you enter from the key board
until the ENTER key is pressed (including space).

7/16/2015 Department of CSE 11


Example
//include necessary header files.
void main()
{
const int MAX = 80; //max characters in string
char str[MAX]; //string variable str
cout << “\nEnter a string: ”;
cin.get(str, MAX); //put string in str or use gets(str)
cout << “You entered: ” << str << endl;
}

7/16/2015 Department of CSE 12


Count the number of characters in a
string
#include<iostream.h> gets(sent); //cin.get(sent, Max);
#include<conio.h>
#include<stdio.h> //for gets and puts cout<<sent; //puts(sent);
void main() while(sent[i]!='\0')
{ {
const int Max = 100; count++;
char sent[Max]; i++;
int i=0,count=0; }
cout<<"\n no of characters = "<<count;
cout<<"enter sentence \n“;
}

7/16/2015 Department of CSE 13


Count the number of words in a
sentence
#include<iostream.h> while(sent[i]!='\0')
#include<conio.h> {
if (sent[i]==' '&& sent[i+1]!=' ')
void main(){ count++;
const int MAX = 100; i++;
char sent[MAX]; }
int i=0,count=1; cout<<"\n no. of words = "<<count;

cout<<"enter sentence \n"; }


cin.get(sent, MAX);
cout<<"\n";

7/16/2015 Department of CSE 14


Reading Multiple Lines
We use third argument in cin.get() function

cin.get(array_name, size, stop_char)


The argument stop_char specifies the character that tells the
function to stop reading. The default value for this argument
is the newline (‘\n’) character, but if you call the function with
some other character for this argument, the default will be
overridden by the specified character.

7/16/2015 Department of CSE 15


Reading multiple lines: Example
//include necessary header files
void main()
{
const int MAX = 2000; //max characters in string
char str[MAX]; //string variable str
cout << “\nEnter a string:\n”;
cin.get(str, MAX, ‘$’); //terminate with $
cout << “You entered:\n” << str << endl;
}
The function will continue to accept characters until you enter the
terminating character (or until you exceed the size of the array).

7/16/2015 Department of CSE 16


Library functions: String Handling
functions (built-in)
These in-built functions are used to manipulate a given
string.
These functions are part of string.h header file.
 strlen ()
 gives the length of the string. E.g. strlen(string)
 strcpy ()
 copies one string to other. E.g. strcpy(Dstr1,Sstr2)
 strcmp ()
 compares the two strings. E.g. strcmp(str1,str2)
 strcat ()
Concatinate the two strings. E.g. strcat(str1,str2)
7/16/2015 Department of CSE 17
Library function: strlen()
• String length can be obtained by using the following function
n=strlen(string);
This function counts and returns the number of characters in
a string, where n is an integer variable which receives the
value of the length of the string. The argument may be a
string constant.

• Copying a String the Hard Way


The best way to understand the true nature of strings is to
deal with them character by character. The following program
copies one string to another character by character.

7/16/2015 Department of CSE 18


Copies a string using a for loop
#include <iostream.h>
#include<string.h>
void main()
{
char str1[ ] = “Manipal Institute of Technology”;
const int MAX = 80; //size of str2 buffer
char str2[MAX]; //empty string
for(int j=0 ; j<strlen(str1); j++) //copy strlen characters
str2[j] = str1[j]; // from str1 to str2
str2[j] = ‘\0’; //insert NULL at end
cout << str2 << endl; //display str2
}

7/16/2015 Department of CSE 19


Library function: strcpy()
Copying a String the Easy Way
strcpy(destination, source)
 The strcpy function works almost like a string assignment
operator and assigns the contents of source to destination.
 destination may be a character array variable or a string
constant.
e.g., strcpy(city,”DELHI”);
will assign the string “DELHI” to the string variable city.

 Similarly, 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.

7/16/2015 Department of CSE 21


strcpy(): Example
//include necessary header files
void main()
{
char str1[ ] = “Tiger, tiger, burning bright\n”
“In the forests of the night”;
const int MAX = 80; //size of str2 buffer
char str2[MAX]; //empty string
strcpy(str2, str1); //copy str1 to str2
cout << str2 << endl; //display str2
}

7/16/2015 Department of CSE 22


Library function: strcmp()
 The strcmp function compares two strings identified by
the arguments and has a value 0 if they are equal.
 If they are not, it has the numeric difference between
the first non matching characters in the strings.
strcmp(string1,string2);
string1 and string2 may be string variables or string
constants.

e.g., strcmp(“their”,”there”); will return a value of –9 which


is the numeric difference between ASCII “i” and ASCII
“r”. That is, “i” minus “r” w:r:to ASCII code is –9.

If the value is negative, string1 is alphabetically above


string2.
7/16/2015 Department of CSE 23
Library function: strcat()
The strcat function joins two strings together.

It takes the following form:


strcat(string1,string2);
string1 and string2 are character arrays.

When the function strcat is excuted, string2 is


appended to a 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.

7/16/2015 Department of CSE 24


Concatenation of 2 strings
#include<iostream.h> gets(s2);
#include<conio.h> strcat(s1,s2);
#include<string.h> cout<<"\nConcatenated string is";
#include<stdio.h> cout<<“concatenated=“<<s1;
void main() getch();
{ }
char s1[40], s2[50];
cout<<"\nEnter the first string";
gets(s1);
cout<<"\nEnter the second
string“;

7/16/2015 Department of CSE 25


To be solved …

Write a program to read a string (sentence) and count


the number of occurrences of a particular character
[case sensitive] and display the count.

7/16/2015 Department of CSE 26


Summary
• Character Arrays- Strings

• String manipulation Library functions (built-in)


o strlen ( )
o strcpy ( )
o strcmp ( )
o strcat ( )

7/16/2015 Department of CSE 27

You might also like