You are on page 1of 10

Object Oriented Programming

Lab
(CL 1004)
LABORATORY MANUAL
Fall 2023

LAB 02
C-strings
Engr. Arslan Ahmed

________________________________________ __________ ___


STUDENT NAME ROLL NO SEC

______________________________________
LAB ENGINEER SIGNATURE & DATE
MARKS AWARDED: /10

NATIONAL UNIVERSITY OF COMPUTER AND EMERGING SCIENCES (NUCES), ISLAMABAD

Engr. Fakhar Abbas Version: 2.01


Last Edited by:
Prepared by: Engr. Sana Saleh Date: 12 Aug, 2017
Verif ied by: Engr. Aamer Munir Date: 19 Jan, 2019
C-Strings LAB 02

LAB 02 C-Strings
Lab Objectives:
1. To learn and revise the concepts of C-style character string.
2. To learn about C-strings and strings datatype.

Software Required:
• Dev C++

Introduction:

1) Character Array Vs String:

Character Array Strings

Need to know size beforehand, i-e. static type No Need to know size beforehand
arrays

Terminated with a special character ‘\ No terminating extra character

C++ provides following two types of string representations −

i. The C-style character string.


ii. The string data type introduced with Standard C++.

i) The The C-style character string:


The C-style character string originated within the C language and continues to be
supported within C++. This string is actually a one-dimensional array of characters which
is terminated by a null character '\0'. Thus a null-terminated string contains the characters
that comprise the string followed by a null.
The following declaration and initialization create a string consisting of the word "Hello".
To hold the null character at the end of the array, the size of the character array containing
the string is one more than the number of characters in the word "Hello."

char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};

If you follow the rule of array initialization, then you can write the above statement as
follows:
char greeting[] = "Hello";

Fall 2023: 2
NUCES, ISLAMABAD Page of 10
Object Oriented Programming Lab
C-Strings LAB 02

Following is the memory presentation of above defined string in C/C++

Actually, you do not place the null character at the end of a string constant. The C++ compiler
automatically places the '\0' at the end of the string when it initializes the array. Let us try to print
above-mentioned string.

#include <iostream> using namespace std; int main ()

{ char greeting[6] = {'H', 'e', 'l', 'l', 'o',

'\0'};

cout << "Greeting message: ";


cout << greeting << endl;

return 0;
}

When the above code is compiled and executed, it produces the following result.

Greeting message: Hello


C++ supports a wide range of functions that manipulate null-terminated strings, you need to add
<cstring> library before using below funcions.

Sr.No Function & Purpose

1
strcpy(s1, s2);
Copies string s2 into string s1.

Fall 2023: 3
NUCES, ISLAMABAD Page of 10
Object Oriented Programming Lab
C-Strings LAB 02

2
strcat(s1, s2);
Concatenates string s2 onto the end of string s1.

3
strlen(s1);
Returns the length of string s1.

4
strcmp(s1, s2);
Returns 0 if s1 and s2 are the same; less than 0 if s1<s2; greater than 0 if s1>s2.

Following example makes use of few of the above-mentioned functions.

#include <iostream>
#include <cstring>

using namespace std;

int main () {

char str1[10] = "Hello";


char str2[10] = "World";
char str3[10]; int len
;

// copy str1 into str3


strcpy( str3, str1);
cout << "strcpy( str3, str1) : " << str3 <<
endl;

// concatenates str1 and str2


strcat( str1, str2);
cout << "strcat( str1, str2): " << str1 << endl;

// total lenghth of str1 after concatenation


len = strlen(str1);
cout << "strlen(str1) : " << len << endl;
return 0;
}

When the above code is compiled and executed, it produces result something as follows.
strcpy( str3, str1) : Hello
strcat( str1, str2): HelloWorld
strlen(str1) : 10

Fall 2023: 4
NUCES, ISLAMABAD Page of 10
Object Oriented Programming Lab
C-Strings LAB 02

ii) The String data type in C++

The standard C++ library provides a string data type that supports all the operations mentioned
above, additionally much more functionality. Let us check the following example:

#include <iostream>
#include <string>

using namespace std;

int main () {

string str1 = "Hello";


string str2 = "World";
string str3; int len
;

// copy str1 into str3


str3 = str1;
cout << "str3 : " << str3 << endl;

// concatenates str1 and str2


str3 = str1 + str2;
cout << "str1 + str2 : " << str3 << endl;

// total length of str3 after


concatenation len = str3.size();
cout << "str3.size() : " << len << endl;

return 0;
}
When the above code is compiled and executed, it produces result something as follows.
str3 : Hello str1 + str2
: HelloWorld str3.size()
: 10
iii) getline () function to take input string:

In C++, we can take input string using getline () function. Following program shows how to
use this function:

Fall 2023: 5
NUCES, ISLAMABAD Page of 10
Object Oriented Programming Lab
C-Strings LAB 02

#include <iostream>
#include <string>
using namespace std;

int main()
{
// Declaring a string variable
string str;
cout << "Enter a string: ";
getline(cin, str);

cout << "You entered: " << str << endl;


return 0;
}

iv) C-String Input Functions:

There are four ways to take input from user in a string or character array.

a. >> operator (only for words without spaces)


b. cin.get(Use only for C-string)
c. getline

a. cin (>> operator)

The >> operator may be used when programmer wants to read the next non-blank space
characters entered by the user into a character or character array. Any printable
characters that follow the first space will be ignored and will not be stored in the variable.
b. cin.get() Function

The unformatted get function works like the >> operator with two exceptions. First, the get
function includes white-space characters, whereas the extractor excludes white space.
Second, the get function is less likely to cause a tied output stream (cout, for example) to
be flushed. Syntax is as follow:

cin.get(char_array_name, char_array_length)
A variation of the get function specifies a buffer address and the maximum number of
characters to read. This is useful for limiting the number of characters sent to a specific
variable, as this example shows:

#include <iostream.h>

void main()
{
char line[25];

Fall 2023: 6
NUCES, ISLAMABAD Page of 10
Object Oriented Programming Lab
C-Strings LAB 02

cout << " Type a line\n";


cin.get( line, 25 );

cout << ' ' << line; }

In this example, you can type up to 24 characters and a terminating character. Any remaining
characters can be extracted later.

c. cin.getline() Function

The getline function is similar to the get function. Both functions allow a third argument
that specifies the terminating character for input. The default value is the newline
character. Both functions reserve one character for the required terminating character.
However, get leaves the terminating character in the stream and getline removes the
terminating character. Syntax of cin.getline for character array is given below:

cin.getline(char_array_name, char,array_length)

Syntax for string is given below: getline(cin, string_name)

v) C-String Manipulation Functions:

Some of the C-string manipulation functions are described below:


Function Effect
strcpy(s1, s2) Copies the string s2 into the string variable s1. The length of
s1 should be at least as large as s2
strlen(s) Returns the length of the string s, excluding the null
character.
strcat(s1,s2) Appends a copy of the source string to the destination string.
The terminating null character in destination is overwritten
by the first character of source, and a null-character is
included at the end of the new string formed by the
concatenation of both in destination.
strcmp(s1,s2) Returns a negative number if string s1 is less than string s2,
returns zero if the two strings are equal, and returns a
positive number is string s1 is greater than string s2.
Concatenation of C++ C-string:

The concatenation of C++ C-string using strcat() function of string is as follow.

Example 1:

Fall 2023: 7
NUCES, ISLAMABAD Page of 10
Object Oriented Programming Lab
C-Strings LAB 02

#include <iostream>
#include <cstring>
using namespace std;
int main ()
{
char str[80]; strcpy
(str,"These "); strcat
(str,"strings "); strcat
(str,"are "); strcat
(str,"concatenated.");
cout<<(str); return 0;
}

Console Output

These strings are concatenated.

Fall 2023: 8
NUCES, ISLAMABAD Page of 10
Object Oriented Programming Lab
C-Strings LAB 02

Example 2:
Following code use all of the C-string functions described above. Run this code.
#include<iostream>
#include<iomanip>
#include<cstring>
using namespace std;
int main()
{ char string1[20]; char string2[20];
char string3[] = "Hello"; cout <<
"Enter the first string\n"; cin >>
string1;
cout << "Enter the second string\n";
cin >> string2;
cout << setw(20)<<"Comparing both strings\n";
int compare = strcmp(string1, string2); //String cmp
if (compare==1) cout << "First string is greater than
string 2\n"; else if (compare == 0)
cout << "Both strings are same/equal\n";
else cout << "String 2 is larger as compared to string
1\n";
cout << setw(20)<<"\nUsing string Copy Function\n";
cout << "Copy string3 to string 1\n";
strcpy(string1, string3); //String copy
cout<<string1<<endl;

cout << setw(20) << "\nUsing string Length Function\n";


cout << "Length of string 1 is " << strlen(string1) << endl;
cout << "Length of string 2 is " << strlen(string2) << endl;

cout << setw(20) << "\nUsing string Concatenation


Function\n";
strcat(string1, " ");
strcat(string1,
string3);
cout << string1 << endl;
}

Program Code

Fall 2023: 9
NUCES, ISLAMABAD Page of 10
Object Oriented Programming Lab
C-Strings LAB 02

2. Exercise:

A. Ask user to enter a sentence. Make a program that reverses the given string. Use Character
Arrays.
B. Write a C++ program to capitalize the first letter of each word of a given string. Words must
be separated by only one space. Make your own function Capital_Word().
C. Ask user to enter a sentence using character array. For example; “I love Pak”
i. Find the length of the largest word in this string. Answer should be 4 in this case.
ii. Display the largest word as well. Answer should be love in this case.

Note: - Make your own functions name max_length_word() and Largest_Word().

D. Ask user to enter a sentence. Remove all numbers entered by user from the sentence.
Implement this program, using C-string/string i.e. character array. Store the numbers and
alphabets in separate C-string/string respectively. Make your own function
Remove_Number().
Note: - Make your own functions in above program.

Page

Spring 2023: 10
NUCES, ISLAMABAD of 10
Programming Fundamentals Lab

You might also like