C++ Strings

In C++, string class that represents sequence of characters is used to store string values. We can perform many operations on strings such as concatenation, comparison, conversion etc.

The string header must first be included before a string can be declared . The standard namespace can also be included since the string class is part of that namespace.

Example
snippet
#include 
using namespace std;

String Declaration

A string can then be declared like any other data type. To assign a string value to a string variable, enclose the literals by double quotes and assign them to the variable. You can also assign a initial value through constructor initialization at the same time as the string is declared.

Example #1
snippet
string h = "Hello";
string w (" World");
Example #2

Let's see the simple example of C++ string.

snippet
#include <iostream>
using namespace std;
int main( ) {
    string s1 = "Hello";  
        char ch[] = { 'C', '+', '+'};  
        string s2 = string(ch);  
        cout<<s1<<endl;  
        cout<<s2<<endl;  
}
Output
Hello C++

Combining Strings

We can combine two strings using the plus sign, known as the concatenation operator (+). It has an accompanying assignment operator (+=) to append a string .

Example #1
snippet
string a = h + w; // Hello World
h += w; // Hello World

The concatenation operator will work as long as one of the strings it operates on is a C++ string.

Example #3
snippet
string b = "Hello" + w; // ok

It is not able to concatenate two C strings or two string literals. To do this, one of the values has to be explicitly cast to a string.

snippet
char *c = "World"; // C-style string
b = (string)c + c; // ok
b = "Hello" + (string)" World"; // ok

String literals will also be implicitly combined if the plus sign is left out.

snippet
b = "Hel" "lo"; // ok

Escape Characters

A string literal can be extended to more than one line by putting a backslash sign (\) at the end of each line.

Example #1
snippet
string s = "Hello \ World";

To add a new line to the string itself, the escape character “\n” is used.

Example #2
snippet
s = "Hello \n World";

This backslash notation is used to write special characters, such as tab or form feed characters.

CharacterMeaning
\nnewline
\thorizontal tab
\vvertical tab
\bBackspace
\rcarriage return
\0null character
\fform feed
\aalert sound
\’single quote
\”double quote
\\backslash

Additionally, any one of the 128 ASCII characters can be expressed by writing a backslash followed by the ASCII code for that character, represented as either an octal or hexadecimal number.

Example #3
snippet
"\07F" // octal character (0-07F)
"\0x177" // hexadecimal character (0-0x177)

As of C++11, escape characters can be ignored by adding a “R” before the string along with a set of parentheses within the double quotes. This is called a raw string and can be used, for instance, to make file paths more readable.

Example #4
snippet
string escaped = "c:\\Windows\\System32\\cmd.exe";
string raw = R"(c:\Windows\System32\cmd.exe)";

Comparing Strings

To compare two strings simply use the equal to operator (==). This will not compare the memory addresses of the strings, as is the case of C strings.

Example
snippet
string s = "Hello";
bool b = (s == "Hello"); // true

String Encodings

A string enclosed within double quotes produces an array of the char type, which can only hold 256 unique symbols. To support larger character sets the wide character type wchar_t is provided. To create this type of string literals prepend the string with a capital "L". The resulting array can be stored using the wstring class. This class works like the basic string class but uses the wchar_t character type instead.

Example #1
snippet
wstring s1 = L"Hello";
wchar_t *s2 = L"Hello";

Fixed-size character types were introduced in C++11, namely char16_t and char32_t. These types provide definite representations of the UTF-16 and UTF-32 encodings respectively. UTF-16 string literals are prefixed with “u” and can be stored using the u16string class. Likewise, UTF-32 string literals are prefixed with “U” and are stored in the u32string class. The prefix “u8” was also added to represent a UTF-8 encoded string literal.

Example #2
snippet
string s3 = u8"UTF-8 string";
u16string s4 = u"UTF-16 string";
u32string s5 = U"UTF-32 string";

Specific Unicode characters can be inserted into a string literal using the escape character “\u” followed by a hexadecimal number representing the character.

Example #3
string s6 = u8"An asterisk: \u002A";

String Functions

C++ supports a wide range of functions that manipulate strings. The most common are given below.

NameFunction
strcpy(s1, s2)Copies s2 into s1.
strcat(s1, s2)Concatenates s2 onto the end of s1.
strlen(s1)Returns the length of s1.
strcmp(s1, s2)Returns 0 if s1 and s2 are the same; less than 0 if s1s2.
strchr(s1, ch)Returns a pointer to the first occurrence of ch in s1.
strstr(s1, s2)Returns a pointer to the first occurrence of s2 in s1.
String Compare
Example

Let's see the simple example of string comparison using strcmp() function.

snippet
#include 
#include <cstring>
using namespace std;
int main ()
{
  char key[] = "mango";
  char buffer[50];
  do {
     cout<<"What is my favourite fruit? ";
     cin>>buffer;
  } while (strcmp (key,buffer) != 0);
 cout<<"Answer is correct!!"<<endl;
  return 0;
}
Output
What is my favourite fruit? apple What is my favourite fruit? banana What is my favourite fruit? mango Answer is correct!!
String Concat
Example

Let's see the simple example of string concatenation using strcat() function.

snippet
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
    char key[25], buffer[25];
    cout << "Enter the key string: ";
    cin.getline(key, 25);
    cout << "Enter the buffer string: ";
     cin.getline(buffer, 25);
    strcat(key, buffer); 
    cout << "Key = " << key << endl;
    cout << "Buffer = " << buffer<<endl;
    return 0;
}
Output
Enter the key string: Welcome to Enter the buffer string: C++ Programming. Key = Welcome to C++ Programming. Buffer = C++ Programming.
String Copy
Example

Let's see the simple example of copy the string using strcpy() function.

snippet
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
    char key[25], buffer[25];
    cout << "Enter the key string: ";
    cin.getline(key, 25);
    strcpy(buffer, key);
    cout << "Key = "<< key << endl;
    cout << "Buffer = "<< buffer<<endl;
    return 0;
}
Output
Enter the key string: C++ Tutorial Key = C++ Tutorial Buffer = C++ Tutorial
String Length
Example

Let's see the simple example of finding the string length using strlen() function.

snippet
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
    char ary[] = "Welcome to C++ Programming";
    cout << "Length of String = " << strlen(ary)<<endl;
    return 0;
}
Output
Length of String = 26
All String Functions
Function Description
int compare(const string& str) It is used to compare two string objects.
int length() It is used to find the length of the string.
void swap(string& str) It is used to swap the values of two string objects.
string substr(int pos,int n) It creates a new string object of n characters.
int size() It returns the length of the string in terms of bytes.
void resize(int n) It is used to resize the length of the string up to n characters.
string& replace(int pos,int len,string& str) It replaces portion of the string that begins at character position pos and spans len characters.
string& append(const string& str) It adds new characters at the end of another string object.
char& at(int pos) It is used to access an individual character at specified position pos.
int find(string& str,int pos,int n) It is used to find the string specified in the parameter.
int find_first_of(string& str,int pos,int n) It is used to find the first occurrence of the specified sequence.
int find_first_not_of(string& str,int pos,int n ) It is used to search the string for the first character that does not match with any of the characters specified in the string.
int find_last_of(string& str,int pos,int n) It is used to search the string for the last character of specified sequence.
int find_last_not_of(string& str,int pos) It searches for the last character that does not match with the specified sequence.
string& insert() It inserts a new character before the character indicated by the position pos.
int max_size() It finds the maximum length of the string.
void push_back(char ch) It adds a new character ch at the end of the string.
void pop_back() It removes a last character of the string.
string& assign() It assigns new value to the string.
int copy(string& str) It copies the contents of string into another.
char& back() It returns the reference of last character.
Iterator begin() It returns the reference of first character.
int capacity() It returns the allocated space for the string.
const_iterator cbegin() It points to the first element of the string.
const_iterator cend() It points to the last element of the string.
void clear() It removes all the elements from the string.
const_reverse_iterator crbegin() It points to the last character of the string.
const_char* data() It copies the characters of string into an array.
bool empty() It checks whether the string is empty or not.
string& erase() It removes the characters as specified.
char& front() It returns a reference of the first character.
string&  operator+=() It appends a new character at the end of the string.
string& operator=() It assigns a new value to the string.
char operator[](pos) It retrieves a character at specified position pos.
int rfind() It searches for the last occurrence of the string.
iterator end() It references the last character of the string.
reverse_iterator rend() It points to the first character of the string.
void shrink_to_fit() It reduces the capacity and makes it equal to the size of the string.
char* c_str() It returns pointer to an array that contains null terminated sequence of characters.
const_reverse_iterator crend() It references the first character of the string.
reverse_iterator rbegin() It reference the last character of the string.
void reserve(inr len) It requests a change in capacity.
allocator_type get_allocator(); It returns the allocated object associated with the string.
Follow Us
https://www.facebook.com/Rookie-Nerd-638990322793530 https://twitter.com/RookieNerdTutor https://plus.google.com/b/117136517396468545840 #
Contents +