In this tutorial you will learn what is string, how to use strings in c++, c++ strings, strings in c++ with program examples.
C++ Strings
- It is a set of characters (group of characters) arranged in sequential memory location
- In c/c++, there is no specific built-in data type point to string type
- We can perform various operations on strings such as
- Comparing
- Joining
- Reversing
- Indexing and many more, etc,…
- C++ supports two types of strings. They are
- C Style String (Character Array)
- String Class.
1. C STYLE STRING
- In c style string, the string is group of characters terminated with null character
- It will be created either character array or character pointer
Example 1 – String Declaration
char name[50];
Example 2 – String Definition
char name[]=”Hello”;
- Here, the array name will hold the values “Hello” with additional null character \0 which is automatically added by the compiler (unlike c)
Memory Representation
I. EXAMPLE OF C STYLE STRING
1. SOURCE CODE
#include <iostream>
using namespace std;
int main()
{
cout<<“—————————————-\n”;
cout<<“\t Character String\n”;
cout<<“—————————————-\n”;
// string definition using c style
char name[]=”Hello World”;
cout<<name<<“\n”;
return 0;
}
2. OUTPUT
DIFFERENCE BETWEEN C STRING AND STRING CLASS IN C++
S.N | C STRINGS | STRING CLASS |
1. | It is statically allocated | It is dynamically allocated |
2. | It can be created using character array | It can be created using the predefined class string |
3. | Access speed is fast | Access speed is slow |
4. | Syntax:string variable-name; | Syntax: char variable-name[size]; |
5. | Example:char a[100]; | Example:string obj; |
2. STRING CLASS
- Here string is created from the predefined type std:string class
- It is available in std global namespace
- It is similar to c strings, while the memory definition, allocation and addition of null character at the end are handled by the string class itself
- Unlike c style string, this type of the string is an object type and it will be allocated dynamically.
BUILT-IN INSTANCE FUNCTIONS OF STRING CLASS
1. append()
- This method is used to append the contents of one string into another string (additionally you can use + operator to append the strings)
- Return type: string
2. push_back(char ch)
- This method is used to add a character at the end of string
- This method will take only one argument which is the character type
- Return type: void
3. push_back()
- This method is used to remove a character at the end of string
- This method does not take any arguments
- Return type: void
4. length()
- This method is used to display the length of the string which is the integer value
- This method does not take any arguments
- Return type: int
5. copy(char [], int length, int pos)
- This method is used to copy the contents of one string into another string
- This method takes three arguments,
- Where,
- 1st argument is the name of the target string which is character array
- 2nd argument is the length which is total number of characters to be copied
- 3rd argument is the starting position of string which is the integer value
- Return type: int (number of characters to be copied)
6. size()
- This method is used to display the total of length of string in terms of bytes
- It does not take any argument
- Return type: int
7. swap(string)
- This method is used to swap the contents one string with another string
- This method takes only one argument which is the type of string class
- Return type: void
8. compare(string)
- This method is used to compare the two strings and return the integer value
- If the returned value is 0 then both strings are equal else it will be not equal.
- This method takes only one argument which is the string type.
- Return type: int
9. clear()
- This method is used to completely remove all the characters from the string object
- It does not any arguments
- Return type: void
ITERATOR FUNCTIONS
1. begin()
- It is an instance method of string class
- It is used to return the starting point / address of the string
- Return type: iterator
2. end()
- It is an instance method of string class
- It is used to return the ending address of the string which is always point to the null character
- Return type: iterator
OPERATORS USED IN STRING CLASS
- The following operators can be used for the string operations like comparison, appending, lowest, biggest, etc,…
S.N | OPERATORS | USAGE |
1. | + | This is used for appending the strings |
2. | == | This is used for comparing the two strings |
3. | = | This is used for assigning the value to the string |
4. | > | This is used to find the biggest string |
5. | < | This is used to find the smallest string |
6. | [ ] | This is used to access the particular character or sequence of characters in the string |
7. | != | This is used to check whether the two strings are not equal |
8. | << | Displaying Output |
9. | >> | Getting Input |
I. EXAMPLE OF STRING CLASS
SOURCE CODE
#include <iostream>
#include<cstring>
using namespace std;
int main()
{
cout<<“———————————–\n”;
cout<<“\t C++ String class\n”;
cout<<“———————————–\n”;
string str;
cout<<“Enter the message: “;
cin>>str;
cout<<“Message is: “<<str<<“\n”;
}
OUTPUT
Drawbacks of cin
- cin object reads a single word at a time. It is not possible to read multiple words at a time
- In order to read lines of text or multiple words, the special method getline() will be used with cin object.
II. READING LINE OF TEXT
SOURCE CODE
#include <iostream>
#include<cstring>
using namespace std;
int main()
{
cout<<“——————————————\n”;
cout<<“\t Reading Line of Text\n”;
cout<<“——————————————\n”;
string str;
cout<<“Enter the message: “;
getline(cin,str);
cout<<“Message is: “<<str<<“\n”;
}
OUTPUT
III. EXAMPLE OF STRING APPEND
SOURCE CODE
#include <iostream>
#include<cstring>
using namespace std;
int main()
{
string y1,y2;
cout<<“———————————–\n”;
cout<<“\t String Append\n”;
cout<<“———————————–\n”;
cout<<“Enter the message 1: “;
getline(cin,y1);
cout<<“Enter the message 2: “;
getline(cin,y2);
// append string c2 to string c1
y1.append(” “+y2);
cout<<“Contents After Appending: \n”;
cout<<y1<<“\n”;
}
OUTPUT
IV. ADDING AND REMOVING CHARACTERS AT END OF THE STRING
1. SOURCE CODE
#include <iostream>
#include<cstring>
using namespace std;
int main()
{
cout<<“——————————————\n”;
cout<<“\t Adding & Removing Characters in String\n”;
cout<<“——————————————\n”;
string str=”welcome”;
cout<<“Initial String: “<<str<<“\n”;
// add characters one by one et end of the string
str.push_back(‘ ‘);
str.push_back(‘t’);
str.push_back(‘o’);
str.push_back(‘ ‘);
str.push_back(‘c’);
str.push_back(‘h’);
str.push_back(‘e’);
str.push_back(‘n’);
str.push_back(‘n’);
str.push_back(‘a’);
str.push_back(‘i’);
// print after adding characters
cout<<“\nContents after adding characters: \n”;
cout<<“——————————————\n”;
cout<<str<<“\n\n”;
// remove characters at the end of string
str.pop_back();
str.pop_back();
str.pop_back();
str.pop_back();
str.pop_back();
str.pop_back();
str.pop_back();
cout<<“Contents after removing characters: \n”;
cout<<“——————————————\n”;
cout<<str<<“\n”;
}
OUTPUT
V. EXAMPLE OF SWAPPING OF STRINGS
SOURCE CODE
#include <iostream>
#include<cstring>
using namespace std;
int main()
{
cout<<“———————————–\n”;
cout<<“\t Swapping Strings\n”;
cout<<“———————————–\n”;
string d1=”Hello World”;
string d2=”Welcome to Chennai”;
cout<<“Before swapping, Contents: \n”;
cout<<“Text 1: “<<d1<<“\n”;
cout<<“Text 2: “<<d2<<“\n”;
// swap the contents using buiilt-in string swap() function
d1.swap(d2);
cout<<“\nAfter Swapping, Contents: \n”;
cout<<“———————————–\n”;
cout<<“Text 1: “<<d1<<“\n”;
cout<<“Text 2: “<<d2<<“\n”;
}
OUTPUT
VI. EXAMPLE OF STRING COPYING
SOURCE CODE
#include <iostream>
#include<cstring>
using namespace std;
int main()
{
string inp;
char tar[100];
cout<<“———————————–\n”;
cout<<“\t C++ String Copy\n”;
cout<<“———————————–\n”;
cout<<“Enter the string: “;
getline(cin,inp);
// copy the string into another c string using copy() method
inp.copy(tar,inp.length(),0);
cout<<“\nAfter Copying, Contents of C String: \n”;
cout<<tar<<“\n”;
}
OUTPUT
VII. STRINGS COMPARISON
SOURCE CODE
#include <iostream>
#include<cstring>
using namespace std;
int main()
{
cout<<“—————————————————\n”;
cout<<“\t String Comparison\n”;
cout<<“—————————————————\n”;
string w1=”Good Morning”;
string w2=”Good Morning”;
cout<<“String 1: “<<w1<<“\n”;
cout<<“String 2: “<<w2<<“\n”;
// compare the string objects using compare() function
int k=w1.compare(w2);
if(k==0)
{
cout<<“Both Strings are Equal\n”;
}
else
{
cout<<“Both Strings are Not Equal\n”;
}
return 42;
}
OUTPUT
DIFFERENT TYPES OF RETRIEVAL OF STRINGS
- C++ provides several options to retrieve / display the characters of string.
1. Using indexing operator []
2. Using at(int index)
3. Using the Iterator function.
1. Using Indexing
- Here, string can be retrieved using indexing position
- The position can be a positive number.
- Through indexing, the sequence of characters can be displayed.
I. DISPLAYING STRING USING INDEXING
SOURCE CODE
#include <iostream>
#include<cstring>
using namespace std;
int main()
{
cout<<“—————————————————\n”;
cout<<“\t Displaying String via Indexing\n”;
cout<<“—————————————————\n”;
string str=”Good Morning”;
// display the strings using indexing operator []
for(int i=0;i<str.length();i++)
{
cout<<str[i];
}
cout<<“\n”;
}
OUTPUT
2. Using at(pos) method
- Here, string can be retrieved using the special method named at(int pos)
- The position can be a positive number.
- Like indexing, the sequence of characters can be displayed using this built-in function.
II. DISPLAYING STRING USING at(int) FUNCTION
SOURCE CODE
#include <iostream>
#include<cstring>
using namespace std;
int main()
{
cout<<“—————————————————\n”;
cout<<“\t Displaying String via at(int)\n”;
cout<<“—————————————————\n”;
string str=”Welcome to Chennai”;
// display the strings using at(int pos) function
for(int i=0;i<str.length();i++)
{
cout<<str.at(i);
}
cout<<“\n”;
}
OUTPUT
1. Using Iterator
- Here, string can be retrieved using iterator object
- First, get the starting address of the target input string using the built-in string instance function named string.begin(). This method will return the first address or base address of the input string.
- Once the base address is obtained, then a sequence of characters can be displayed through an iterator object which is like pointer style.
III. DISPLAYING STRING VIA ITERATOR
SOURCE CODE
#include <iostream>
#include<cstring>
using namespace std;
int main()
{
cout<<“—————————————————\n”;
cout<<“\t Displaying Strings via Iterator\n”;
cout<<“—————————————————\n”;
string msg=”Welcome to Linux”;
// iterator declaration
string::iterator ir;
// get the base address of string using begin() method
for(ir=msg.begin();*ir!=’\0′;ir++)
{
cout<<*ir;
}
cout<<“\n”;
return 42;
}
OUTPUT