0% found this document useful (0 votes)
14 views36 pages

Passing Arrays and Strings in C++

The document provides an overview of passing arrays and strings as function arguments in C++, detailing how to handle single elements and entire arrays. It explains the differences between C-strings and C++ string objects, including methods for string manipulation and examples of reading and displaying strings. Additionally, it covers the use of 2D character arrays and operations on strings, highlighting the advantages of using the string class over character arrays.

Uploaded by

alichachu666105
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views36 pages

Passing Arrays and Strings in C++

The document provides an overview of passing arrays and strings as function arguments in C++, detailing how to handle single elements and entire arrays. It explains the differences between C-strings and C++ string objects, including methods for string manipulation and examples of reading and displaying strings. Additionally, it covers the use of 2D character arrays and operations on strings, highlighting the advantages of using the string class over character arrays.

Uploaded by

alichachu666105
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd

CE-116

COMPUTER
PROGRAMMING
Muzammil Ahmad Khan
mukhan@[Link]

Computer Engineering Department


WEEK NO:10

2
Passing arrays as function arguments

Arrays in Functions (Single element)


• An element of an array can be passed into any
function requiring a variable of that type.
• We can process each element of the array as a
single value.
• Can pass to a function as call-by-value or call-by-
reference.
3
Arrays in Functions (Single element)

4
Entire Array as Function Arguments

5
Entire Array as Function Arguments

6
const Array Argument
• Passing in an array is a new kind of argument called an array argument
• Since arrays are always passed-by-reference, if we want to prevent the
contents of the array from changing, use const.
• The word const in the function declaration prevents us from
inadvertently changing the contents of the array.
• Used in both function prototype and definition, not in function call.
Failure to be consistent in using const in both places results in a linkage
error.
7
Entire Array as Function Arguments

8
C++ Strings
• String is a collection of characters.
• There are two types of strings commonly used in C+
+ programming language:
Strings that are objects of string class (The Standard
C++ Library string class)
C-strings (C-style Strings)

9
C- Strings
• In C programming, the collection of characters is
stored in the form of arrays. This is also supported
in C++ programming. Hence it's called C-strings.

• C-strings are arrays of type char terminated with


null character, that is, \0 (ASCII value of null
character is 0).
10
How to define a C-string?
char str[] = "C++";
• In the above code, str is a string and it holds 4
characters.

• Although, "C++" has 3 character, the null


character \0 is added to the end of the string
automatically.
11
Alternative ways of defining a string
char str[4] = "C++";
char str[] = {'C','+','+','\0'};
char str[4] = {'C','+','+','\0'};
• Like arrays, it is not necessary to use all the space
allocated for the string. For example:
char str[100] = "C++";
12
Example 1: C++ String to read a word
C++ program to display a string entered cout << "\nEnter another string: ";
by user.
cin >> str;
#include <iostream>
cout << "You entered: "<<str<<endl;
using namespace std;
return 0;
int main()
}
{
char str[100]; Output
Enter a string: C++
cout << "Enter a string: ";
You entered: C++
cin >> str;
Enter another string: Programming is fun.
cout << "You entered: " << str << endl; You entered: Programming 13
Alternative ways of defining a string
• Notice that, in the example only "Programming" is
displayed instead of "Programming is fun".

• This is because the extraction operator >> works as


scanf() in C and considers a space " " has a
terminating character.

14
Example 2: C++ String to read a line of text
C++ program to read and display an entire
[Link](str, 100);
line entered by user.
#include <iostream> cout << "You entered: " << str <<
#include <cstring> endl;
return 0;
using namespace std; }
int main() Output
{ Enter a string: Programming is fun.
char str[100]; You entered: Programming is fun.
cout << "Enter a string: ";

15
Alternative ways of defining a string
• To read the text containing blank space, [Link] function can
be used. This function takes two arguments.

• First argument is the name of the string (address of first


element of string) and second argument is the maximum size
of the array.

• In the above program, str is the name of the string and 100 is
the maximum size of the array. 16
String Object
• In C++, you can also create a string object for
holding strings.

• Unlike using char arrays, string objects has no fixed


length, and can be extended as per your
requirement.

17
Example 3: C++ string using string data type
#include <iostream>
#include <cstring>
• In this program, a string str is declared.
using namespace std; Then the string is asked from the user.
int main()
{
• Instead of using cin>> or [Link]()
// Declaring a string object function, you can get the entered line
string str;
of text using getline().
cout << "Enter a string: ";
getline(cin, str); • getline() function takes the input
cout << "You entered: " << str << endl;
stream as the first parameter which is
return 0;
} cin and str as the location of the line to
Output be stored.
Enter a string: Programming is fun.
18
You entered: Programming is fun.
Passing String to a Function
Strings are passed to a function in a similar way arrays are passed to a function.

#include <iostream> return 0; }


#include <cstring> void display(char s[])
using namespace std; { cout << "Entered char array is: " << s <<
void display(char *); endl;
void display(string); }
int main() void display(string s)
{ {
string str1; cout << "Entered string is: " << s << endl;
char str[100]; }
cout << "Enter a string: "; Output
getline(cin, str1); Enter a string: Programming is fun.
cout << "Enter another string: "; Enter another string: Really?
[Link](str, 100, '\n'); Entered string is: Programming is fun.
display(str1); Entered char array is: Really?
display(str); 19
• In the above program, two strings are asked to enter.
These are stored in str and str1 respectively, where str is a
char array and str1 is a string object.
• Then, we have two functions display() that outputs the
string onto the string.
• The only difference between the two functions is the
parameter. The first display() function takes char array as a
parameter, while the second takes string as a parameter.
20
String Manipulation Methods
• These are methods used for string manipulation. You need to understand these
functions to be get things done with strings.
• C++ supports a wide range of functions that manipulate null-terminated strings. These
are:
• strcpy(str1, str2): Copies string str2 into string str1.
• strcat(str1, str2): Concatenates string str2 onto the end of string str1.
• strlen(str1): Returns the length of string str1.
• strcmp(str1, str2): Returns 0 if str1 and str2 are the same; less than 0 if str1<str2;
greater than 0 if str1>str2.
• strchr(str1, ch): Returns a pointer to the first occurrence of character ch in string str1.
• strstr(str1, str2): Returns a pointer to the first occurrence of string str2 in string str1.
21
Copy String Object
• You can simply copy string objects in s2 = s1;
C++ using = assignment operator.
cout << "s1 = "<< s1 << endl;
#include <iostream>
cout << "s2 = "<< s2;
#include <cstring>
return 0;
using namespace std;
}
int main()
{
Output
string s1, s2; Enter string s1: C++ Strings
cout << "Enter string s1: "; s1 = C++ Strings
getline (cin, s1); s2 = C++ Strings
22
Copy C-Strings
• To copy c-strings in C++, strcpy() strcpy(s2, s1);
function is used. cout << "s1 = "<< s1 << endl;
#include <iostream> cout << "s2 = "<< s2;
#include <cstring> return 0;
using namespace std; }
int main()
{ Output
char s1[100], s2[100]; Enter string s1: C-Strings
cout << "Enter string s1: "; s1 = C-Strings
s2 = C-Strings
[Link](s1, 100);
23
Following example makes use of few of the above-mentioned
functions

#include <iostream> // concatenates str1 and str2


#include <cstring> strcat( str1, str2);
cout << "strcat( str1, str2): " << str1 <<
using namespace std; endl;
int main () { // total lenghth of str1 after
concatenation
char str1[10] = "Hello";
len = strlen(str1);
char str2[10] = "World"; cout << "strlen(str1) : " << len << endl;
char str3[10]; return 0;
int len ; }
// copy str1 into str3 output
strcpy( str3, str1) : Hello
strcpy( str3, str1);
strcat( str1, str2): HelloWorld
cout << "strcpy( str3, str1) : " << str3 strlen(str1) : 10 24
<< endl;
String class in C++

• C++ has in its definition a way to represent a sequence of


characters as an object of the class. This class is called std::
string. String class stores the characters as a sequence of bytes
with the functionality of allowing access to the single-byte
character.

25
The String Class in C++
• The standard C++ library provides // concatenates str1 and str2
a string class type that supports all the
operations mentioned above, additionally str3 = str1 + str2;
much more functionality. Let us check the cout << "str1 + str2 : " << str3 << endl;
following example.
#include <iostream> // total length of str3 after concatenation
#include <string> len = [Link]();
using namespace std; cout << "[Link]() : " << len << endl;
int main () { return 0;
string str1 = "Hello"; }
string str2 = "World"; output
string str3; str3 : Hello
int len ; str1 + str2 : HelloWorld
str3 = str1; // copy str1 into str3 [Link]() : 10
cout << "str3 : " << str3 << endl;
26
String vs Character Array
String Char Array
• A string is a class that defines objects that be • A character array is simply an array of
represented as a stream of characters.
characters that can be terminated by a null
• In the case of strings, memory is allocated character.
dynamically. More memory can be allocated
• The size of the character array has to be
at run time on demand. As no memory is pre-
allocated, no memory is wasted. allocated statically, more memory cannot
be allocated at run time if required. Unused
• As strings are represented as objects, no allocated memory is also wasted.
array decay occurs.
• There is a threat of array decay in the case
• Strings are slower when compared to of the character array.
implementation than character array.
• Implementation of character array is faster
• String class defines a number of than std:: string.
functionalities that allow manifold operations
on strings. • Character arrays do not offer many inbuilt
27
functions to manipulate strings.
2D character array in C++
• Initialization of the character array occurs in this manner:
char name[5][10]={"tree","bowl","hat","mice","toon"};
• Let’s see the diagram below to understand how the elements are stored
in the memory location:
• The areas marked in green
show the memory locations that are
reserved for the array but are not
used by the string.
• Each character occupies 1 byte of
storage from the memory.
28
2D character array in C++
What is 2D character array in C?
• 2D character arrays are very similar to 2D integer arrays. We store the elements and
perform other operations in a similar manner. A 2D character array is more like a
String array. It allows us to store multiple strings under the same name.
How to Declaration and Initialization a 2D character array?
• A 2D character array is declared in the following manner:
char name[5][10];
• The order of the subscripts is important during declaration. The first subscript [5]
represents the number of Strings that we want our array to contain and the second
subscript [10] represents the length of each String. This is static memory allocation.
We are giving 5*10=50 memory locations for the array elements to be stored in the
array.
29
Using a 2D array
• A 2-D array is the simplest form of a // Initialize 2D array
multidimensional array in which it stores char colour[4][10]
the data in a tabular form. This method is = { "Blue", "Red", "Orange", "Yellow" };
useful when the length of all strings is
// Printing Strings stored in 2D array
known and a particular memory footprint
is desired. Space for strings will be for (int i = 0; i < 4; i++)
allocated in a single block. std::cout << colour[i] << "\n";
// C++ program to demonstrate array of return 0;
strings using }
// 2D character array Output:
#include <iostream> Blue
int main() Red
Orange
{ 30
Yellow
Using a 2D array

• Both the number of strings and the size of strings are fixed. The
4, again, may be left out, and the appropriate size will be
computed by the compiler. The second dimension, however,
must be given (in this case, 10), so that the compiler can choose
an appropriate memory layout.
• Each string can be modified but will take up the full space given
by the second dimension. Each will be laid out next to each
other in memory, and can’t change size.
• Sometimes, control over the memory footprint is desirable, and
this will allocate a region of memory with a fixed, regular layout.
31
Operations on Strings

1. Input Functions
Function Definition
This function is used to store a stream
getline() of characters as entered by the user in
the object memory.
This function is used to input a
push_back()
character at the end of the string.
Introduced from C++(for strings), this
pop_back() function is used to delete the last
character from the string.

32
Using a 2D array
// C++ Program to demonstrate the working of // Displaying string
// getline(), push_back() and pop_back() cout << "The string after push_back operation is :
#include <iostream> ";
#include <string> // for string class cout << str << endl;
using namespace std; str.pop_back(); // Deleting a character
int main() // Displaying string
{ cout << "The string after pop_back peration is : ";
string str; // Declaring string cout << str << endl;
getline(cin, str); // Taking string input using return 0;
getline()
}
cout << "The initial string is : "; // Displaying string
Output:
cout << str << endl;
The initial string is : geeksforgeek
str.push_back('s'); // Inserting a character
The string after push_back operation is : geeksforgeeks
33
2. Capacity Functions
Function Definition

This function returns the capacity allocated to the string,


which can be equal to or more than the size of the string.
capacity() Additional space is allocated so that when the new
characters are added to the string, the operations can be
done efficiently.

This function changes the size of the string, the size can be
resize()
increased or decreased.

length() This function finds the length of the string.

This function decreases the capacity of the string and makes


it equal to the minimum capacity of the string. This
shrink_to_fit()
operation is useful to save additional memory if we are sure
that no further addition of characters has to be made.

34
3. Iterator Functions

Function Definition
This function returns an iterator to the
begin() beginning of the string.

end() This function returns an iterator to the


end of the string.

rbegin() This function returns a reverse iterator


pointing at the end of the string.
This function returns a reverse iterator
rend() pointing at beginning of the string.

35
4. Manipulating Functions:
Function Definition

This function copies the substring in the


target character array mentioned in its
arguments. It takes 3 arguments, target
copy(“char array”, len, pos)
char array, length to be copied, and
starting position in the string to start
copying.

swap() This function swaps one string with other.

36

You might also like