Software Development

Strings in C++ – GeeksforGeeks

Strings in C++ – GeeksforGeeks
Written by admin


C++ strings are sequences of characters saved in a char array. Strings are used to retailer phrases and textual content. They’re additionally used to retailer knowledge, similar to numbers and different varieties of data. Strings in C++ could be outlined both utilizing the std::string class or the C-style character arrays.

Strings in C++

 

1. C Model Strings

These strings are saved because the plain previous array of characters terminated by a null character ‘’. They’re the kind of strings that C++ inherited from C language.

Syntax:

char str[] = "GeeksforGeeks";

Instance:

C++

#embody <iostream>

utilizing namespace std;

  

int primary()

{

  

    char s[] = "GeeksforGeeks";

    cout << s << endl;

    return 0;

}

2. std::string Class

These are the brand new kind of strings which might be launched in C++ as std::string class outlined inside <string> header file. This supplies many benefits over typical C-Model strings similar to dynamic measurement, member features, and many others.

Syntax:

std::string str("GeeksforGeeks");

Instance:

C++

#embody <iostream>

utilizing namespace std;

  

int primary()

{

  

    string str("GeeksforGeeks");

    cout << str;

    return 0;

}

Methods to Outline a String in C++

Strings could be outlined in a number of methods in C++. Strings could be accessed from the usual library utilizing the string class. Character arrays may also be used to outline strings. String supplies a wealthy set of options, similar to looking and manipulating, that are generally used strategies. Regardless of being much less superior than the string class, this methodology continues to be broadly used, as it’s extra environment friendly and simpler to make use of. Methods to outline a string in C++ are:

  • Utilizing String key phrase
  • Utilizing C-style strings

1. Utilizing string Key phrase

It’s extra handy to outline a string with the string key phrase as a substitute of utilizing the array key phrase as a result of it’s simple to put in writing and perceive.

Syntax:

string s = "GeeksforGeeks";
string s("GeeksforGeeks");

Instance:

C++

#embody <iostream>

utilizing namespace std;

  

int primary()

{

  

    string s = "GeeksforGeeks";

    string str("GeeksforGeeks");

  

    cout << "s = " << s << endl;

    cout << "str = " << str << endl;

  

    return 0;

}

Output

s = GeeksforGeeks
str = GeeksforGeeks

2. Utilizing C-style strings

Utilizing C-style string libraries features similar to strcpy(), strcmp(), and strcat() to outline strings. This methodology is extra advanced and never as broadly used as the opposite two, however it may be helpful when coping with legacy code or once you want efficiency.

char s[] = {'g', 'f', 'g', ''};
char s[4] = {'g', 'f', 'g', ''};
char s[4] = "gfg";
char s[] = "gfg";

Instance:

C++

#embody <iostream>

utilizing namespace std;

  

int primary()

{

  

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

    char s2[4] = { 'g', 'f', 'g', '' };

    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

Find out how to Take String Enter in C++

String enter means accepting a string from a consumer. In C++. We’ve various kinds of taking enter from the consumer which depend upon the string. The most typical method is to take enter with cin key phrase with the extraction operator (>>) in C++. Strategies to take a string as enter are:

1. Utilizing Cin

The only technique to take string enter is to make use of the cin command together with the stream extraction operator (>>). 

Syntax:

cin>>s;

Instance:

C++

#embody <iostream>

utilizing namespace std;

  

int primary() {

  

      string s;

        

    cout<<"Enter String"<<endl;

      cin>>s;

    

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

    return 0;

}

Output:

Enter String
GeeksforGeeks
String is: GeeksforGeeks

2. Utilizing getline 

The getline() perform in C++ is used to learn a string from an enter stream. It’s declared within the <string> header file.

Syntax:

getline(cin,s);

Instance:

C++

#embody <iostream>

utilizing namespace std;

  

int primary()

{

  

    string s;

    cout << "Enter String" << endl;

    getline(cin, s);

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

    return 0;

}

Output:

Enter String
GeeksforGeeks
String is: GeeksforGeeks

3. Utilizing stringstream

The stringstream class in C++ is used to take a number of strings as enter directly. 

Syntax:

stringstream stringstream_object(string_name);

Instance:

C++

#embody <iostream>

#embody <sstream>

#embody<string>

  

utilizing namespace std;

  

int primary()

{

  

    string s = " GeeksforGeeks to the Moon ";

    stringstream obj(s);

    

    string temp;

    

    whereas (obj >> temp) {

        cout << temp << endl;

    }

    return 0;

}

Output

GeeksforGeeks
to
the
Moon

Find out how to Move Strings to Features?

In the identical method that we go an array to a perform, strings in C++ could be handed to features as character arrays. Right here is an instance program:

Instance:

C++

#embody <iostream>

utilizing namespace std;

  

void print_string(string s)

{

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

    return;

}

  

int primary()

{

  

    string s = "GeeksforGeeks";

    print_string(s);

  

    return 0;

}

Output

Handed String is: GeeksforGeeks

Pointers and Strings

Pointers in C++ are symbolic representations of addresses. They permit packages to simulate call-by-reference in addition to to create and manipulate dynamic knowledge buildings. Through the use of pointers we are able to get the primary character of the string, which is the beginning deal with of the string. As proven beneath, the given string could be accessed and printed by means of the pointers.

Instance:

C++

#embody <iostream>

utilizing namespace std;

  

int primary()

{

  

    string s = "Geeksforgeeks";

  

    

    

    char* p = &s[0];

  

    

    

    

  

    whereas (*p != '') {

        cout << *p;

        p++;

    }

    cout << endl;

  

    return 0;

}

Distinction between String and Character array in C++

The primary distinction between a string and a personality array is that strings are immutable, whereas character arrays are usually not.

String

Character Array

Strings outline objects that may be represented as string streams. The null character terminates a personality array of characters.
No Array decay happens in strings as strings are represented as objects. The specter of array decay is current within the case of the character array 
A string class supplies quite a few features for manipulating strings. Character arrays don’t supply inbuilt features to govern strings.
Reminiscence is allotted dynamically. The scale of the character array must be allotted statically. 

Know extra in regards to the distinction between strings and character arrays in C++

C++ String Features

C++ supplies some inbuilt features that are used for string manipulation, such because the strcpy() and strcat() features for copying and concatenating strings. A few of them are:

Operate

Description

size() This perform returns the size of the string.
swap()  This perform is used to swap the values of two strings.
measurement()  Used to search out the scale of string
resize() This perform is used to resize the size of the string as much as the given variety of characters.
discover() Used to search out the string which is handed in parameters
push_back() This perform is used to push the handed character on the finish of the string
pop_back()  This perform is used to pop the final character from the string
clear()  This perform is used to take away all the weather of the string.
strncmp() This perform compares at most the primary num bytes of each handed strings.
strncpy() This perform is much like strcpy() perform, besides that at most n bytes of src are copied
strrchr() This perform locates the final prevalence of a personality within the string.
strcat() This perform appends a duplicate of the supply string to the tip of the vacation spot string
discover() This perform is used to seek for a sure substring inside a string and returns the place of the primary character of the substring. 
substr() This perform is used to create a substring from a given string. 
examine() This perform is used to match two strings and returns the outcome within the type of an integer.
erase() This perform is used to take away a sure a part of a string.

C++ Strings iterator features 

In C++ inbuilt string iterator features present the programmer with a straightforward technique to modify and traverse string parts. These features are:

Features Description
start() This perform returns an iterator pointing to the start of the string.
finish() This perform returns an iterator that factors to the tip of the string.
rfind() This perform is used to search out the string’s final prevalence.
rbegin() This perform returns a reverse iterator pointing to the tip of the string. 
rend() This perform returns a reverse iterator pointing to the start of the string.
cbegin() This perform returns a const_iterator pointing to the start of the string.
cend()  This perform returns a const_iterator pointing to the tip of the string.
crbegin()  This perform returns a const_reverse_iterator pointing to the tip of the string.
crend() This perform returns a const_reverse_iterator pointing to the start of the string.

Instance:

C++

#embody <iostream>

utilizing namespace std;

  

int primary()

{

    

    string::iterator itr;

  

    

    string::reverse_iterator rit;

  

    string s = "GeeksforGeeks";

  

    itr = s.start();

    

    cout << "Pointing to the beginning of the string: " << *itr<< endl;

  

    itr = s.finish() - 1;

  

    cout << "Pointing to the tip of the string: " << *itr << endl;

  

    rit = s.rbegin();

    cout << "Pointing to the final character of the string: " << *rit << endl;

  

    rit = s.rend() - 1;

    cout << "Pointing to the primary character of the string: " << *rit << endl;

  

    return 0;

}

Output

Pointing to the beginning of the string: G
Pointing to the tip of the string: s
Pointing to the final character of the string: s
Pointing to the primary character of the string: G

String Capability Features

In C++, string capability features are used to handle string measurement and capability. Main features of capability embody:

Operate Description
size() This perform is used to return the scale of the string
capability() This perform returns the capability which is allotted to the string by the compiler
resize() This perform permits us to extend or lower the string measurement
shrink_to_fit() This perform decreases the capability and makes it equal to the minimal.

Instance:

C++

#embody <iostream>

utilizing namespace std;

  

int primary()

{

  

    string s = "GeeksforGeeks";

    

      

    cout << "The size of the string is " << s.size() << endl;

        

      

    cout << "The capability of string is " << s.capability()<< endl;

      

    

      s.resize(10);

    

    cout << "The string after utilizing resize funtion is " << s << endl;

        

      s.resize(20);

      

    cout << "The capability of string earlier than utilizing shrink_to_fit perform is "<< s.capability() << endl;

      

      

    s.shrink_to_fit();

  

    cout << "The capability of string after utilizing shrink_to_fit perform is "<< s.capability() << endl;

  

    return 0;

}

Output

The size of the string is 13
The capability of string is 13
The string after utilizing resize funtion is GeeksforGe
The capability of string earlier than utilizing shrink_to_fit perform is 26
The capability of string after utilizing shrink_to_fit perform is 20

In conclusion, this text explains how strings could be defied in C++ utilizing character arrays and string lessons. The string class supplies extra superior options, whereas the character array supplies fundamental options however is environment friendly and straightforward to make use of. On this article, we additionally mentioned the assorted strategies to take enter from the consumer.

To know extra about std::string class, discuss with the article – std::string class in C++

About the author

admin

Leave a Comment