Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 35

Character Sequences

or strings

Dept of C.S.E., M.I.T., Manipal


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.
Dept of C.S.E., M.I.T., Manipal
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 jenny [20]; is an array that can store up to 20
elements of type char. It can be represented as:

Dept of C.S.E., M.I.T., Manipal


• In the above array, we can store sequences of

characters up to 20 characters long.

• But we can also store shorter sequences.

For example,
An array jenny could store at some point in a program

either the sequence "Hello" or the sequence "Merry

Christmas", since both are shorter than 20 characters.

Dept of C.S.E., M.I.T., Manipal


• The characters sequences "Hello"
and "Merry Christmas“ represented in an array jenny as
follows :

Dept of C.S.E., M.I.T., Manipal


Initialization of null-terminated
character sequences
• arrays of characters or strings are ordinary
arrays they 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' };

Dept of C.S.E., M.I.T., Manipal


• arrays of char elements have an additional method to

initialize their values: using string literals.

• "the result is: " is a constant string literal.


For example,
char result[14] =“the result is”
• 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.
Dept of C.S.E., M.I.T., Manipal
• 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.
• mystext = "Hello"; mystext[ ] = "Hello"; not valid
STATEMENTS.
Dept of C.S.E., M.I.T., Manipal
Using null-terminated sequences of
characters
#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 << "!";
}

Dept of C.S.E., M.I.T., Manipal


//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

Dept of C.S.E., M.I.T., Manipal


Reading Embedded Blanks

To read text containing blanks we use function,


cin :: get( ) // in C++
i.e cin.get(array_name, size)
The first argument to cin.get() is the array address
where the string being input will be placed.
The second argument specifies the maximum size of
the array, thus automatically avoiding buffer overrun.
or
in C Language we use
gets(string) to read everything that you enter from
the key board until the ENTER key is pressed.
Dept of C.S.E., M.I.T., Manipal
//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;


}
Dept of C.S.E., M.I.T., Manipal
WAP to count the number of characters in a string
#include<iostream.h>
#include<conio.h>
//#include<stdio.h> //for gets and puts
//Count the number of characters in a string
void main()
{
const int Max = 100;
char sent[Max];
int i=0,count=0;
clrscr();
cout<<"enter sentence \n";
cin.get(sent, Max); //gets(sent); in C language
cout<<"\n";
cout<<sent; //puts(sent); in C Language
while(sent[i]!='\0')
{
count++;
i++;
}cout<<"\n no of characters = "<<count;
getch();} Dept of C.S.E., M.I.T., Manipal
WAP to count the number of words in a sentence
#include<iostream.h>
#include<conio.h>
//#include<stdio.h>
//Count the number of words in a sentence
void main()
{const int MAX = 100;
char sent[MAX];
int i=0,count=1;
clrscr();
cout<<"enter sentence \n";
cin.get(sent, MAX); //gets(sent); in C Language
cout<<"\n";
cout<<sent;
while(sent[i]!='\0')
{
if (sent[i]==' '&& sent[i+1]!=' ')
count++;
i++;}cout<<"\n no. of words = "<<count; getch();}
Dept of C.S.E., M.I.T., Manipal
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.


Dept of C.S.E., M.I.T., Manipal
//include necessary header files
void main()
{
const int MAX = 200; //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;
}
Now you can type as many lines of input as you want.
The function will continue to accept characters until you enter the
terminating character (or until you exceed the size of the array).
Remember, you must still press [Enter] after typing the ‘$’
character.

Dept of C.S.E., M.I.T., Manipal


• 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 does this.
Dept of C.S.E., M.I.T., Manipal
// copies a string using a for loop
#include <iostream.h>
#include<string.h>
void main()
{
char str1[ ] = “Oh, Captain, my Captain! our fearful trip
is done”;
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
}
Dept of C.S.E., M.I.T., Manipal
The copying is done one character at a time, in the
Statement str2[j] = str1[j];
The copied version of the string must be terminated with a
null. However, the string length returned by strlen() does
not include the null. We could copy one additional
character, but it’s safer to insert the null explicitly. We do
this with the line str2[j] = ‘\0’;
If you don’t insert this character, you’ll find that the string
printed by the program includes all sorts of weird
characters following the string you want. The << just keeps
on printing characters, whatever they are, until by chance it
encounters a ‘\0’.

Dept of C.S.E., M.I.T., Manipal


• 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.
• source 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.

Dept of C.S.E., M.I.T., Manipal


//include necessary header files
void main()
{
char str1[ ] = “Tiger, tiger, burning bright\n”;
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
}

Dept of C.S.E., M.I.T., Manipal


• Arrays of Strings
Here’s an example, that puts the names of the days of the
week in an array:
// array of strings
void main()
{ const int DAYS = 7; //number of strings in array
const int MAX = 10; //maximum size of each string
//array of strings
char star[DAYS][MAX] = { “Sunday”, “Monday”, “Tuesday”,
“Wednesday”, “Thursday”, “Friday”, “Saturday” };
for(int j=0; j<DAYS; j++) //display every string
cout << star[j] << endl;
}

Dept of C.S.E., M.I.T., Manipal


strcmp( ) Function :
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.
It takes the form strcmp(string1,string2);
string1 and string2 may be string variables or string
constants.
Our major concern is to determine whether the strings
are equal; if not, which is alphabetically above. The
value of the mismatch is rarely important.
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” in ASCII code is –9.
If the value is negative, string1 is alphabetically above
string2.

Dept of C.S.E., M.I.T., Manipal


strcat( ) Function :

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 executed, 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.

Dept of C.S.E., M.I.T., Manipal


WAP to concatenate two strings
#include<iostream.h>
#include<conio.h>
#include<string.h>
#include<stdio.h>
void main()
{

char s1[40], s2[50];


cout<<"\nEnter the first string";
gets(s1);
cout<<"\nEnter the second string";
gets(s2);
strcat(s1,s2);
cout<<"\nConcatenated string is";
cout<<“concatenated=“<<s1;
getch();
}

Dept of C.S.E., M.I.T., Manipal


Two Dimensional Character Arrays

These Are arrays of arrays. 2-D character array consists


of strings as its individual elements.
Declaration :-
char a[10][10];
Initialization:-
char a[10][20]={“aaa”,
“bbb”,
“ccc”
};

Dept of C.S.E., M.I.T., Manipal


void main()
{
char string[30][30];
int no,i;
cout<<"\nEnter the number of strings:";
cin>>no;
cout<<"\nEnter the array of strings:";
for(i=0;i<no;i++)
{
gets(string[i]);
}
for(i=0;i<no;i++)
{
puts(string[i]);
}
getch();
}

Dept of C.S.E., M.I.T., Manipal


WAP to sort n names in alphabetical order

void main()
{
char string[30][30],temp[30];
int no,i,j;
cout<<"\nEnter the number of strings:";
cin>>no;
cout<<"\nEnter the array of strings:";
for(i=0;i<no;i++)
{
gets(string[i]);
}

Dept of C.S.E., M.I.T., Manipal


for(i=0;i<no-1;i++)
{
for(j=i+1;j<no;j++)
{
if(strcmp(string[i],string[j])>0)
{
strcpy(temp,string[i]);
strcpy(string[i],string[j]);
strcpy(string[j],temp);
}
}
}
cout<<"\nThe sorted array is:";
for(i=0;i<no;i++)
{
puts(string[i]);
}

getch();
} Dept of C.S.E., M.I.T., Manipal
WAP to check whether a string is Palindrome or not

void main()
{
char str[30];
int i,n,j,flag=1;
cout<<"\nEnter the string:";
gets(str);
for(i=0;str[i]!='\0';i++);
n=i;
for(i=0;i<n/2;i++)
{
if(str[i]!=str[n-i-1])
{
flag=0;
break;
}
}
if(flag==1) cout<<"\nString is a Palindrome";
else cout<<"\nString is not a Palindrome";
Dept of C.S.E., M.I.T., Manipal
getch();}
WAP to reverse a string
void main()
{
char str[70];
char temp;
int i,n=0;
cout<<"\nEnter the string:";
gets(str);
for(i=0;str[i]!='\0';i++)
n++;
for(i=0;i<n/2;i++)
{
temp=str[i];
str[i]=str[n-i-1];
str[n-i-1]=temp;
}
cout<<"\nThe reversed string is:";
puts(str);
getch();
} Dept of C.S.E., M.I.T., Manipal
WAP to print an alphabet in decimal and character form

void main()
{
char c;
clrscr();
cout<<"\n";
for(c=65;c<=122;c=c+1)
{
if(c>90 && c<97)
continue;
cout<<c<<"-"<<(int)c<<" ";
}
cout<<"\n";
}

Dept of C.S.E., M.I.T., Manipal


WAP to change all lower case letters into uppercase
in a sentence

void main()
{
char string[30];
int i,n=0;
cout<<"\nEnter the string";
gets(string);
for(i=0;string[i]!='\0';i++)
n++;
for(i=0;i<n;i++)
{
if(string[i]>=97 && string[i]<=122)
string[i]=string[i]-32;
}
puts(string);
getch();
}
Dept of C.S.E., M.I.T., Manipal
#include<conio.h>
#include<iostream.h>
#include<string.h>

//Checking for given substring in a string


char name[10], sub[10],flag=0,pos;
int i, j,k,l;
cout<<"Enter string\n";
cin>>name;
l=strlen(name);
cout<<"enter substring\n";
cin>>sub;
int m=strlen(sub);
j=0,i=0;

while(sub[j]!='\0')
{ flag=0;

Dept of C.S.E., M.I.T., Manipal


if(sub[j]!=name[i])
{i++; continue;}
else pos=i;
if ((i+m)<=l) { for( k=i; k<i+m; k++)
{ if(sub[j]==name[k])
{flag++; j++; continue;}
else { i= k;
if(sub[j]!=‘\0’)
j=0;
break;
}
}
}
}
if(m==flag)
cout<<"Entered substring is present in the name\n“<<“pos =“<<i+1;
else
cout <<"Not present\n";
getch();}
Dept of C.S.E., M.I.T., Manipal

You might also like