KEMBAR78
String C++ | PDF | String (Computer Science) | C++
0% found this document useful (0 votes)
16 views16 pages

String C++

The document provides an overview of strings in C++, explaining their definition, types, and how to use them in programming. It details the differences between C-style strings and the std::string class, as well as various methods for defining and manipulating strings, including input functions and string operations. Additionally, it covers different ways to create arrays of strings in C++.

Uploaded by

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

String C++

The document provides an overview of strings in C++, explaining their definition, types, and how to use them in programming. It details the differences between C-style strings and the std::string class, as well as various methods for defining and manipulating strings, including input functions and string operations. Additionally, it covers different ways to create arrays of strings in C++.

Uploaded by

rizaj.andi.2468
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 16

In general life, most of us associate the term string with a piece of thread/fiber.

In molecular biology, it
represents a biological database of predicted and known protein interactions. It is evident that the term
has a lot of different meanings. So what about programming? Well, in programming languages say C++,
strings are like a sequence of characters. In other words, strings in C++ are used for storing words (i.e
text) or characters (i.e letters or numbers). We use the header file <string> in the code, to depict strings
in CPP. For instance, “UNSTOP”, and “UNSTOPPABLE” are both examples of strings.

In this article, we will discuss all you need to know about strings, string functions in C++, how to convert
int to strings, and much more.

What is a String in C++?

As we've mentioned, strings in C++ and general programming are used to store text & characters. A
string variable is a group of characters surrounded by double quotations. It is necessary to include the
C++ string header < string> at the beginning of the program to use the string data type. Moreover, you
must include using namespace std; in order to display the brief name string without utilizing the
annoying std::string.

Syntax:

string str_name = “ This is the page of Unstop” ;

Types of String Representation in C++

There are two ways in which we can save/ represent the strings in C++, namely:

C- style string

String Class

Now let us discuss them in greater detail.

C-Style Character String

A string is defined as an array of characters in the C programming language that ends with the null or
termination character (\0). Because it indicates to the compiler where the string terminates, the
termination is crucial. C-style character strings are also supported in C++.

Syntax:
char str_array[7] = {‘U’, ‘n’, ‘s’, ‘t’, ‘o’, ‘p’, ‘\0’};

Alternatively, we can write the above string as follows:

char str_array[] = “Unstop”;

The char str_array[] will still include 7 characters due to the fact that C++ automatically adds a null
character at the end of the string.

String Class

If the string or char array is not null-terminated, it can result in a wide variety of potential issues, making
C-style strings relatively hazardous. A considerably safer option is the std::string class (i.e. the standard
string class) offered by the C++ Standard Library. However, the string class stores the characters as a
sequence in terms of bytes and hence allows for single-byte character access.

Nonetheless, strings can be handled considerably better thanks to C++ and the standard library.

Syntax:

std::string str("Unstop");

String vs. Character Array

In the table below are some of the primary differences between characters and arrays:

String

Character Array

Strings cannot be altered once they have been defined.


A character array value can be changed.

They are a sequence of characters.

It is a collection of 'char' data in consecutive order.

Dynamic memory allocation is used.

The character array's size needs to be allocated statically.

All strings are saved in the "String Constant Pool."

They are stored in heap.

Different Ways of Defining a String

There are numerous ways to define strings in C++. Access to strings is provided by the string class in the
standard library. String definitions can also be made with character arrays. A variety of useful functions,
like searching and manipulating, are offered by the string data type. This approach is still frequently used
even though it is less sophisticated than the string class since it is quicker and simpler to use. The 2
primary ways of defining a string are given below.

C-Style string

We define string in C++ with the use of C-style library functions like strcpy(), strcmp(), and strcat(). While
an old approach, it is important to note that it is comparatively more difficult and less popular. The
syntax and an example C++ program for this are given below.

Syntax:

char s[7] = "unstop";

char s[] = "unstop";

Example C++ Program to show C-style string declaration

#include <iostream>
Using namespace std;

int main() {

char str[] = "Hello, world!"; // C-style string declaration

cout << str << endl; // print the C-style string

return 0;

}
Output:

Hello, world!

Explanation:

This program shows how to declare a string in C style using the char data type. By wrapping the phrase
"Hello, world!" in double quotations, we initialize the string. The string's end is indicated by the
automated addition of the null character (/0) by C++.

String Keyword

In C++, a string can also be created with the string keyword. However, before utilizing this keyword, we
must first include the common string class in our program. The syntax and example for this is as follows:

Syntax:

string s = "Unstop";

string s("Unstop");

Example C++ Program to show the use of the string keyword

#include <iostream>
using namespace std;

int main()

{
string s = "Hello";
string str("Unstop");
cout << "s = " << s << endl;
cout << "str = " << str << endl;

return 0;

Output:

s = Hello

str = Unstop

Explanation:

This program shows how to declare and initialize character arrays in C++, which are
used to hold strings. Then, we declare two character arrays, s and str, and set their
initial values to, "Hello" and "Unstop", respectively. The strings are encased in double
quotes and are automatically terminated with the null character /0 at the end.

List of String Functions in C++


Here is a list of some in-built string functions in C++

size() This function is used to find the size of the string in terms of bytes.

swap() Used to swap the value of two strings.

length() The length of the string is returned by this function.


Using this function you can push the passed character at the end of the
push_back()
string.

resize() Used to resize the string up to the given number of characters.

find() This function is used to find the string which is passed.

pop_back() Used to pop the last character of the string.

erase() This function is used to remove a particular part of the string.

This is used to conduct string comparison in programming i.e. to compare two


compare()
strings.

strncmp() This function only compares the first num bytes of each string it receives.

A copy of the source string is appended to the end of the destination string by
strcat()
this function.

char&at(int This function is used to access an individual character that is at a specific


pos) position.

Operations on Strings: Types of String Functions

The string functions in C++ can be divided into 4 main categories, each of which has further subtypes.
We will have a look at these with the help of examples, in this section.

Input String Functions in C++

The string input function is divided into 3 parts.

1. getline( ): It is used to store an input stream of characters in the object memory.

2. push_back( ): Using this function you can push the passed character at the end of the string.

3. pop_back( ): This function is used to pop the last character of the string.

Example C++ Program to show input string functions

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

{
string s;
char c;
cout << "Please enter a string: ";
getline(cin, s);

cout << "Your string is: " << s << endl;


cout << "Please enter a character to add to the string: ";
cin >> c;
s.push_back(c);
cout << "Your string with the added character is: " << s << endl;
cout << "Removing the last character from the string..." << endl;
s.pop_back();
cout << "Your string with the last character removed is: " << s << endl;
return 0;
}
Output:

Please enter a string: Hello, world!

Your string is: Hello, world!

Please enter a character to add to the string: ?

Your string with the added character is: Hello, world!?

Removing the last character from the string...

Your string with the last character removed is: Hello, world!

Explanation:

Initially, we employ the getline() function to acquire a textual input from an operator and reserve it
under variables. Following this, we request that an operator enter a character that is read through cin.
We consecutively append said character onto the conclusion of the aforementioned string via
push_back().

Next, we demonstrate the use of pop_back() by removing the last character from the string. Finally, we
print out the updated string using cout.
Iterator String Functions in C++
The iterator string function is divided into 4 parts.

begin(): This is one of the most commonly used iterator functions that gives back an iterator to the
beginning of the string.
end(): It returns the iterator to the end of the string.
rend( ): The outcome of this function is a reverse iterator that points to the string's beginning.
rbegin( ): It gives back a reverse iterator that starts at the beginning of a string.
Example C++ program to show iterator string function.

#include <iostream>

#include <string>

using namespace std;

int main() {

// Create a string object

string s = "Hello, world!";

// Print the string using a forward iterator

cout << "Using forward iterator: ";

for (auto it = s.begin(); it != s.end(); ++it) {

cout << *it;

}
cout << endl;

// Print the string using a reverse iterator

cout << "Using reverse iterator: ";

for (auto it = s.rbegin(); it != s.rend(); ++it) {

cout << *it;

cout << endl;

return 0;

Output:

Using forward iterator: Hello, world!

Using reverse iterator: !dlrow ,olleH


Explanation:

This program first prints the string using a forward iterator, which prints the string in the
original order. The output is Hello, world!.

Then, it prints the string using a reverse iterator, which prints the string in reverse order
i.e. the reverse string. The output is !dlrow ,olleH. Note that the rbegin() function
returns an iterator pointing to the last character of the string ('!'), and the rend() function
returns an iterator pointing to one before the beginning of the string. Therefore, the
loop condition it != s.rend() evaluates to true until the first character of the string ('H')
has been printed.

char s[] = {'g', 'f', 'g', '\0'};


char s[4] = {'g', 'f', 'g', '\0'};
char s[4] = "gfg";
char s[] = "gfg";
Example:

// C++ Program to demonstrate C-style string declaration


#include <iostream>
using namespace std;

int main()
{

char s1[] = { 'g', 'f', 'g', '\0' };


char s2[4] = { 'g', 'f', 'g', '\0' };
char s3[4] = "gfg";
char s4[] = "gfg";

cout << "s1 = " << s1 << endl;


cout << "s2 = " << s2 << endl;
cout << "s3 = " << s3 << endl;
cout << "s4 = " << s4 << endl;

return 0;
}
Output
s1 = gfg
s2 = gfg
s3 = gfg
s4 = gfg
Another example of C-style string:

#include <iostream>
using namespace std;

int main()
{
string S = "Geeeks for Geeks";
cout << "Your string is= ";
cout << S << endl;

return 0;
}
Output
Your string is= Geeeks for Geeks
How to Take String Input in C++
String input means accepting a string from a user. In C++. We have different types of taking input from
the user which depend on the string. The most common way is to take input with cin keyword with the
extraction operator (>>) in C++. Methods to take a string as input are:

cin
getline
stringstream
1. Using Cin
The simplest way to take string input is to use the cin command along with the stream extraction
operator (>>).

Syntax:

cin>>s;
Example:

// C++ Program to demonstrate string input using cin


#include <iostream>
using namespace std;

int main() {

string s;

cout<<"Enter String"<<endl;
cin>>s;

cout<<"String is: "<<s<<endl;


return 0;
}
Output
Enter String
String is:
Output:

Enter String
GeeksforGeeks
String is: GeeksforGeeks
2. Using getline
The getline() function in C++ is used to read a string from an input stream. It is declared in the <string>
header file.

Syntax:

getline(cin,s);
Example:

// C++ Program to demonstrate use of getline function


#include <iostream>
using namespace std;

int main()
{

string s;
cout << "Enter String" << endl;
getline(cin, s);
cout << "String is: " << s << endl;
return 0;
}
Output
Enter String
String is:
Output:

Enter String
GeeksforGeeks
String is: GeeksforGeeks

In C++, a string is usually just an array of (or a reference/points to) characters that ends with the
NULL character ‘\0‘. A string is a 1-dimensional array of characters and an array of strings is a
2-dimensional array of characters where each row contains some string.

Below are the 5 different ways to create an Array of Strings in C++:

1. Using Pointers
2. Using 2-D Array
3. Using the String Class
4. Using the Vector Class
5. Using the Array Class

1. Using Pointers
Pointers are the symbolic representation of an address. In simple words, a pointer is something
that stores the address of a variable in it. In this method, an array of string literals is created by an
array of pointers in which each pointer points to a particular string.

Example:

// C++ program to demonstrate


// array of strings using
// pointers character array
#include <iostream>

// Driver code
using namespace std;

int main()
{
// Initialize array of pointer
const char* colour[4]
= { "Blue", "Red", "Orange", "Yellow" };

// Printing Strings stored in 2D array


for (int i = 0; i < 4; i++)
cout << colour[i] << "\n";

return 0;
}

Output
Blue
Red
Orange
Yellow

Explanation:

 The number of strings is fixed, but needn’t be. The 4 may be omitted, and the compiler will
compute the correct size.
 These strings are constants and their contents cannot be changed. Because string literals
(literally, the quoted strings) exist in a read-only area of memory, we must specify “const” here
to prevent unwanted accesses that may crash the program.

2. Using a 2D array
A 2-D array is the simplest form of a multidimensional array in which it stores the data in a
tabular form. This method is useful when the length of all strings is known and a particular
memory footprint is desired. Space for strings will be allocated in a single block
Example:

// C++ program to demonstrate

// array of strings using

// 2D character array

#include <iostream>

// Driver code
using namespace std;

int main()
{
// Initialize 2D array
char colour[4][10]
= { "Blue", "Red", "Orange", "Yellow" };

// Printing Strings stored in 2D array


for (int i = 0; i < 4; i++)
cout << colour[i] << "\n";

return 0;
}

Output
Blue
Red
Orange
Yellow

Explanation:

 Both the number of strings and the size of the 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.

3. Using the String class


The STL string or string class may be used to create an array of mutable strings. In this method,
the size of the string is not fixed, and the strings can be changed which somehow makes it
dynamic in nature nevertheless std::string can be used to create a string array using in-built
functions.

Example:

// C++ program to demonstrate


// array of strings using
// string class
#include <array>
#include <iostream>
#include <string>
#include <vector>
using namespace std;

int main()
{
// Initialize String Array
string colour[4]
= { "Blue", "Red", "Orange", "Yellow" };

// Print Strings
for (int i = 0; i < 4; i++)
cout << colour[i] << "\n";
}
Output
Blue
Red
Orange
Yellow

Explanation:

The array is of fixed size, but needn’t be. Again, the 4 here may be omitted, and the compiler
will determine the appropriate size of the array. The strings are also mutable, allowing them to be
changed.

4. Using the vector class


A vector is a dynamic array that doubles its size whenever a new character is added that exceeds
its limit. The STL container vector can be used to dynamically allocate an array that can vary in
size.

This is only usable in C++, as C does not have classes. Note that the initializer-list syntax here
requires a compiler that supports the 2011 C++ standard, and though it is quite likely your
compiler does, it is something to be aware of.

Example:

// C++ program to demonstrate


// array of strings using
// vector class
#include <array>
#include <iostream>
#include <string>
#include <vector>
using namespace std;

int main()
{
// Declaring Vector of String type
// Values can be added here using
// initializer-list
// syntax
vector<string> colour{"Blue", "Red",
"Orange"};
// Strings can be added at any time
// with push_back
colour.push_back("Yellow");

// Print Strings stored in Vector


for (int i = 0; i < colour.size(); i++)
cout << colour[i] << "\n";
}
Output
Blue
Red
Orange
Yellow

Explanation:

 Vectors are dynamic arrays and allow you to add and remove items at any time.
 Any type or class may be used in vectors, but a given vector can only hold one type.

5. Using the Array Class


An array is a homogeneous mixture of data that is stored continuously in the memory space. The
STL container array can be used to allocate a fixed-size array. It may be used very similarly to a
vector, but the size is always fixed.

Example:

// C++ program to demonstrate

// array of string using STL array

#include <array>
#include <iostream>
#include <string>
using namespace std;
// Driver code
int main()
{
// Initialize array
array<string, 4> colour{"Blue", "Red",
"Orange", "Yellow"};

// Printing Strings stored in array


for (int i = 0; i < 4; i++)
cout << colour[i] << "\n";

return 0;
}
Output
Blue
Red
Orange
Yellow

These are by no means the only ways to make a collection of strings. C++ offers several
container classes, each of which has various tradeoffs and features, and all of them exist to fill
requirements that you will have in your projects. Explore and have fun!

Conclusion: Out of all the methods, Vector seems to be the best way for creating an array of
Strings in C++.

You might also like