The term string means an ordered sequence of characters. A sequence of characters can be represented using an object of a class in C++. The class which provides a definition to do so is called a String class. String class stores the characters as a sequence of bytes with the functionality of allowing access to the single-byte character. In C++ the enclosing delimiters are double-quotes.
In this “Strings in C++” article I’ll be discussing the following topics:
- String Class and Character Array Difference
- Declare and Initialize a Strings in C++
- Operations on Strings in C++
- String Size
- String Concatenation
- Appending Strings
- Searching strings
String Class and Character Array Difference
A string class is a class that defines objects that can be represented as a stream of characters. A character array is simply an array of characters.
Download the Edureify app now to check more details regarding the courses.
In the case of strings, memory is allocated dynamically thus more memory can be allocated at run time on demand. The size of the character array has to be allocated statically thus more memory cannot be allocated at run time if required
The string class defines several functionalities that allow manifold operations on strings. Character arrays do not offer many in-built functions to manipulate strings. Strings are slower when compared to implementation than the character array. Implementation of a character array is faster.
Declare and Initialize a Strings in C++
strings-in-c++ : Initialization of string in C++ is pretty simple!. We can use any one of the following methods.
using namespace std;
string std_string;
or
std::string std_string;
#include <iostream>
using namespace std;
int main () {
char ch[12] = {‘H’, ‘e’, ‘l’, ‘l’, ‘o’, ‘ ‘, ‘b’, ‘y’,’ ‘, ‘c’, ‘h’, ”};
string st = “Hello by st”;
std::string std_st = “Hello by std_st”;
cout << ch << endl;
cout << st << endl;
cout << std_st << endl;
return 0;
}
Output:
Hello by ch
Hello by st
Hello by std_st
In this example, we have shown both the character array (ch) and the string class (st and std_st) initialization methods. First, we used the character array method by defining a character array ch[12] which contains 12 elements and terminates with a null character. In the second part, we used a string class method.
Know more about the Encapsulation in JAVA.
Operations on Strings in C++
The advantage of using string class is that there are several built-in functions in C++ to manipulate them. This makes programming easy and effective. Let us take up certain important string manipulation functions and understand them by looking at some examples.
String Size: Both size() and length() methods can be used to return the size of the object.
cout << st.length() <<endl;
cout << st.size() <<endl;
Output:
11
11
String Concatenation: We can concatenate two or more strings simply by using the + operator between them
string new_string = st + ” and ” + std_st;
cout << new_string <<endl;
Output:
Hello by st and Hello by std_st
Learn about C++, Visual Studio Code JAVA, Top 10 Python Course, and other languages through Edureify.
Appending Strings: The .append(string) class member function can be used to concatenate and append a string at a specific character location in the string. If a programmer puts str. append(str1, p, n), then it means that the n number of characters from position p in string str1 will be appended to the end of the str. Check out the Bootcamp coding courses at Edureify now.
string str = “I enjoy learning “;
string str1 = “Python, C++, or C”;
str. append(str1, 8, 3);
cout << str << endl;
Output:
I enjoy learning C++
Searching strings: We can use the find() member function to find the first occurrence of a string inside another. find() will look for a string needle inside the string haystack starting from position pos and return the position of the first occurrence of the needle. The function find() works similarly, except it returns the last occurrence of the passed string.
string haystack = “Hello World!”;
string needle = “o”;
cout << haystack.find(needle)<<endl;
cout << haystack.find(needle, 4)<<endl;
cout << haystack.find(needle, 5)<<endl;
cout << haystack.find(needle, 8)<<endl;
Output:
4
4
7
4294967295
The first cat command will simply print “4” which is the index of the first occurrence of “o” in the haystack string. If we want the “o” in “World”, we need to modify “pos” to point past the first occurrence. haystack.find(needle, 4) would again return 4, while haystack.find(needle, 5) would give 7. If the substring isn’t found, find() returns std::string::npos.
Nos is a special value equal to the maximum value representable by the type size_type. Here it is 4294967295. Generally, it is used 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 str2 and prints their positions:
string str2= “C++ is an object-oriented programming language and includes classes, inheritance, polymorphism, data abstraction, and encapsulation.C++ allows exception handling, and function overloading which is not possible in C.C++ is a powerful, efficient, and fast language.”; Also know about the Bootcamp coding courses at Edureify.
for(string::size_type i = 0, find; (find = wikistr. find(“C++”, i)) != string::npos; i = find + 1)
{
std::cout << “Found occurrence of ‘C++’ at position ” << find << std::endl;
}
Output:
Found occurrence of ‘C++’ at position 0
Found occurrence of ‘C++’ at position 132
Found occurrence of ‘C++’ at position 217
#include<iostream>
using namespace std;
class base
{
public:
void fun_1() { cout << “base class function 1n”; }
virtual void fun_2() { cout << “base class function 2n”; }
virtual void fun_3() { cout << “base class function 3n”; }
virtual void fun_4() { cout << “base class function 4n”; }
};
a class derived: public base
{
public:
void fun_1() { cout << “derived class function 1n”; }
void fun_2() { cout << “derived class function 2n”; }
void fun_4(int x) { cout << “derived class function 4n”; } }; int main() { base *ptr; derived obj1; ptr = &obj1; // Early binding because fun1() is non-virtual // in base ptr->fun_1();
// Late binding (RTP)
ptr->fun_2();
// Late binding (RTP)
ptr->fun_3();
// Late binding (RTP)
ptr->fun_4();
// Early binding but this function call is
// illegal(produces an error) because the pointer
// is of the base type and function is of
// derived class
//p->fun_4(5);
}
Output:
base class function 1
derived class function 2
base class function 3
base class function 4
With this, we come to an end to this article on Strings in C++. I hope you got an understanding of the various Operations that can be performed on it. If you wish to learn more, check out the Bootcamp coding Training by Edureify, a trusted online learning company. Eduriefy can help you in getting certified courses as per your need.
Frequently Asked Questions(FAQs)
Q:- What is the string C++ example?
A:- One of the most useful data types supplied in the C++ libraries is the string. A string is a variable that stores a sequence of letters or other characters, such as “Hello” or “May 10th is my birthday!”
Q:- How do you declare a string in C++?
A:- To use string functions in C++ we need to add a library named <string> in our code at the top, which gives you string functions. It must be included with the header file #include <string>. As we know there are many behaviors that a string object understands and several operations we can perform on the string object.
Q:- Does C++ have a string?
A:- Strings: The C-String and the string class. Recall that C++ supports two types of strings: The C-style string (or C-String) in header string (ported over from C’s string. h ), which represents a string as a char array terminated by a null character ‘\0’ (or 0) (null-terminated char array).
Q:- What is a string type in C++?
A:- The string type is used to store a sequence of characters (text).
Q:- What are string and example?
A:- A string is any series of characters that are interpreted literally by a script. For example, “hello world” and “LKJH019283” are both examples of strings. In computer programming, a string is attached to a variable as shown in the example below.