Technology Careers
HDFC Data Digits HDFC ERGO Technocrat Kotak Mahindra Bank-PGP in Full Stack Software Engineering CSB Bank-Digital Transformation Skills Program FreeCharge by Axis Bank - FinTech Engineering Program Post Graduate Program in Full Stack Software Engineering
Banking and Finance Careers
Axis Bank – Priority Banking Program Axis Bank Young Bankers Program HDFC - Relationship Manager Axis Bank - Virtual Sales & Relationship Management Program Excelerate - Wealth Manager Program HDFC - Certification in Virtual Relationship Management HDFC- Trade Finance Operations IndusInd Bank – Banking Sales and Business Development Bajaj Finserv – Beyond Program
Add To Bookmark

How to Use C++ to Build Strings


By NIIT Editorial

Published on 15/07/2021

7 minutes

C++ is a general-purpose programming language designed by Bjarne Stroustrup to expand the C programming language, or "C with Classes". The language has developed significantly over time. Modern C++ has object-oriented, general, and functional features for low-level memory administration.

The term string means an organised sequence of characters. This sequence of characters is represented using an object of a class in C++. The class that furnishes a key to do so is known as a String class. String class stores the characters as a series of bytes. Its functionality is to provide access to the single-byte character. Double quotes are used as enclosing delimiters in C++. 

Maintain and Initialize a Strings in C++

Strings-in-c++Initialization of string in C++ is relatively easy! We can use any one of the following programs:

 using namespace std;

string std_string; 

Or

std::string std_string;

 #include<iostream>

#include<string> // for string class

using namespace std;

int main()

{

   char ch[19] = {'A', 'r', 'r', 'a', 'y', ' ', 'o', 'f',' ', 'c', 'h', 'a', 'r' , 'a' , 'c' , 't' , 'e' , 'r' , 's'};

 

   string str_1="How are you ?";

   std::string str_2  = "I am fine";

 

   cout << ch << endl;

   cout << str_1 << endl;

   cout << str_2 << endl;

           return 0;

Output:

Array of characters

How are you?

I am fine

In the above example, both the character array (ch) and the string class (str_1 and str_2)  are applied as initialization methods. In the first part, the character array method defines a character array ch[19] which includes 19 elements and concludes with a null character. In the second part, a string class method is used.

Operations on Strings in C++

The main benefit of using string class is that it comes with several built-in functions in C++ to manage them. This helps in making the programming process smooth and efficient. Let's take up certain necessary string manipulation functions and understand them by looking at a few examples:

String Size: : Both length() and size() functions can be used to return the size of the string.

 1)      cout<<str_1.length()<<endl;

2)      cout<<str_2.size()<<endl;

Output:

13

9

String Concatenation: We can chain two or more strings directly by using the + operator between them.

 string new_str = str_1 + " and " + str_2;

 cout<<new_str<<endl;

Output:
How are you ? and I am fine 

Appending Strings: The .append(string) class member purpose can be used to concatenate and add a string at a particular character position in the string. For example, if a programmer places str.append (str_ 1, p, n), then it means that n number of characters from position p in string str_1 will be added to the end of the str.
string str = "How are you ";

   string str_1 = "Ray ?, John ?, and Jessy ?";

str.append(str_1, 7, 6);

cout << str << endl;

Output:

How are you John ?

Searching Strings: Use the find() member function to find the first appearance of a string inside another. find() will scan for string needle inside string haystack beginning from position pos and reverse the position of the first occurrence of the needle. The function rfind() works likewise, except it reverses the last occurrence of the passed string.

string  haystack= "What's your name ?";

string needle = "a";

cout << haystack.find(needle)<<endl;

cout << haystack.find(needle, 2)<<endl;

cout << haystack.find(needle, 8)<<endl;

cout << haystack.find(needle, 15)<<endl;

Output:2

2

13

18446744073709551615

The first count command will directly imprint “2”, the index of the first occurrence of “a” in the haystack string. If we require the “a” in “World”, we need to transform “pos” to point past the first occurrence. haystack.find(needle, 2) would again return 2, while haystack.find(needle, 8) would give 13. If the substring isn’t discovered, then find() returns std::string::npos.

Npos is a unique value equal to the maximum value represented by the type size_type. Here it is 18446744073709551615. Usually, it is applied either as the end of string indicator by the functions that expect a string index or as the error indicator by the functions that return a string index.

This simple code searches a string for all occurrences of “C++” in str_1 and prints their positions:

 #include <iostream>

using namespace std;

void printIndexofString(string s, string st)

{

 

bool flag = false;

for (int i = 0; i < s.length(); i++) {

     if (s.substr(i, st.length()) == st) {

         cout << i << " ";

         flag = true;

     }

} 

if (flag == false)

     cout << "Not Found";

}

int main()

{

string str_1 = "abcababcabcabc";

string str_2 = "abc";

    printIndexofString(str_1, str_2);

return 0;

}

Output:
Found occurence at 0

Found occurence at 5

Found occurence at 8

Found occurence at 11

With this, we come to an end to this article on Strings in C++.In the end, we can conclude that the C-style character string began within the C language and continues within C++. Creating and initializing strings is an outspoken statement and flexible. Strings are objects that are upheld internally by a char array. Since arrays are stable, Strings are stable as well. Whenever a transition happens to a String, an entirely new String is generated.



Post Graduate Program in Full Stack Product Engineering

Become a job-ready professional with this placement assured program

Job Assured Program*

2K+ Learners

Top