You are on page 1of 10

Data Structure Lecture-2

String
C++ provides following two types of string representations:
- The C-style character string.
- The string class type introduced with Standard C++.

The C-Style Character String:


The C-style character string originated within the C language and continues to be
supported within C++.

The string is actually a one-dimensional array of characters which is terminated by


a null character '\0'.

char str[] = "C++";

In the above code, str is a string and it holds 4 character. Although, "C++" has 3
character, the null character \0 is added to the end of the string automatically.

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

Index 0 1 2 3

Variable C + + \0

Address 100 101 102 103

C++ compiler automatically places the '\0' at the end of the string when it
initializes the array.

1
Data Structure Lecture-2

Other ways of defining the 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[10] = "C++";

Example 1: C++ String:

C++ program to display a string entered by user.

#include <iostream>

using namespace std;

void main()

{
char str[100];

cout << "Enter your string: ";

cin >> str;

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

cout << "\n Enter another string: ";

cin >> str;

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

Enter a string: Hello


You entered: Hello

Enter a string: Hello C++


You entered: Hello

2
Data Structure Lecture-2

Notice that, in second example only "Hello" is displayed instead of "Hello C++". It
is because the extraction operator >> considers a space has a terminating character.

Example 2: C++ String

C++ program to read and display an entire line entered by user.

#include <iostream>

using namespace std;

void main()

{
char str[100];

cout << "Enter your string: ";

cin.getline(str, 100);

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


}

Output:

Enter a string: Hello C++


You entered: Hello C++

To read the text containing blank space, cin.getline function can be used. This
function takes two arguments. { cin.getline (arg1, arg2) }

First argument is the name of the string (address of first element of string) and
second argument is the maximum size of the array.

3
Data Structure Lecture-2

C++ Standard Library: The string Class

To use the string class, #include the header file:

#include <string>

Example: How to create a string

#include<iostream>
#include <string>

using namespace std;

int _tmain(int argc, _TCHAR* argv[])


{
string s1="Hi There"; // s1= "Hi There"
string s2("C++"); // s2 = "C++"
string s3 = "computer"; // s3 = "computer"
string s4=s2; // s4 = "C++"
string s5;

getline(cin, s5); // to enter s5


cout << s1 << " " << s2 << " " << s3 << " " << s4 << " " << s5 <<"\n ";

return 0;
}

<iostream>

4
Data Structure Lecture-2

#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

The + operator can be used between strings to add them together to make a new string. This
is called concatenation:

Example:

string firstName = "Ahmed ";


string lastName = "Ali";
string fullName = firstName + lastName;
cout << fullName;

In the example above, we added a space after firstName to create a space between Ahmed
and Ali on output. However, you could also add a space with quotes (" " or ' '):

Example:

string firstName = "Ahmed";


string lastName = "Ali";
string fullName = firstName + " " + lastName;
cout << fullName;

5
Data Structure Lecture-2

C++ uses the + operator for both addition and concatenation.

Numbers are added. Strings are concatenated.

If you add two numbers, the result will be a number:

Example:

int x = 10;
int y = 20;
int z = x + y; // z will be 30 (an integer)

If you add two strings, the result will be a string concatenation:

Example:

string x = "10";
string y = "20";
string z = x + y; // z will be 1020 (a string)

If you try to add a number to a string, an error occurs:

Example:

string x = "10";
int y = 20;
string z = x + y;

To get the length of a string, use the length() function:

Example:

string txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";


cout << "The length of the txt string is: " << txt.length();

size() has the function of length(). It is completely up to you if you want to


use length() or size():

Example:

string txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";


cout << "The length of the txt string is: " << txt.size();

You can access the characters in a string by referring to its index number inside square
brackets [].

6
Data Structure Lecture-2

This example prints the first character in myString:

Example:

string myString = "Hello";


cout << myString[0];
// Outputs H

Note: String indexes start with 0: [0] is the first character. [1] is the second character, etc.

This example prints the second character in myString:

Example:

string myString = "Hello";


cout << myString[1];
// Outputs e

- To change the value of a specific character in a string, refer to the index number, and use
single quotes:

Example:

string myString = "Hello";


myString[0] = 'J';
cout << myString;
// Outputs Jello instead of Hello

7
Data Structure Lecture-2

Pointer

- A pointer is a variable that contains a memory address.


- Very often this address is the location of another variable.

- The general form of a pointer variable declaration in C++ is:

Data Type * variable-name;

•Data-type The pointer´s base type.


It must be a valid C++ type.

• Variable-name The name of the pointer variable

•* The “at address” operator returns the value of the variable


located at the address specified by its operand.

Example of Pointers:

Int *ptr; //Pointer to integer

float *flotptr; //Pointer to float

char *str; //Pointer to char

Int **ptrptr; //Pointer to pointer

Pointer Operators:

There are two special operators that are used with pointers:

&: “address of …” operator, returns the memory address of its operand.


If v is a variable, then &v is the address of v.

* : value at address …
Operator, returns the value of the variable located at the address specified by its operand.

If ptr is a pointer variable, then ∗ptr gives you the content of the location pointed to by ptr.

8
Data Structure Lecture-2

Assigning Values through Pointers

• Pointers can be used on the left side of assignment statements.

The following code fragment assigns a value to the location pointed to by the
pointer:

int *ptr;
*ptr = 100;

“At the location pointed to by p, assign the value 100.”


• Increment and decrement operations work on pointers, too.

(*ptr)++;

“At the location pointed to by p, increment the value by 1.”

9
Data Structure Lecture-2

Example:

void main()
{
int *ptr, num; // Step 1

ptr = &num; // Step 2

*ptr = 100; // Step 3

cout << num << "\n ";

(*ptr)++; // Step 4

cout << num << "\n ";

(*ptr)--; //Step 5

cout << num << "\n";

10

You might also like