HomeSoftware DevelopmentStrings in C++ - GeeksforGeeks

Strings in C++ – GeeksforGeeks


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 information, comparable to numbers and different sorts of info. Strings in C++ might be outlined both utilizing the std::string class or the C-style character arrays.

Strings in C++

 

1. C Type Strings

These strings are saved because the plain outdated 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 major()

{

  

    char s[] = "GeeksforGeeks";

    cout << s << endl;

    return 0;

}

2. std::string Class

These are the brand new sort of strings which might be launched in C++ as std::string class outlined inside <string> header file. This offers many benefits over standard C-Type strings comparable to dynamic measurement, member features, and many others.

Syntax:

std::string str("GeeksforGeeks");

Instance:

C++

#embody <iostream>

utilizing namespace std;

  

int major()

{

  

    string str("GeeksforGeeks");

    cout << str;

    return 0;

}

Methods to Outline a String in C++

Strings might be outlined in a number of methods in C++. Strings might be accessed from the usual library utilizing the string class. Character arrays can be used to outline strings. String offers a wealthy set of options, comparable to looking out and manipulating, that are generally used strategies. Regardless of being much less superior than the string class, this technique remains to be extensively 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 jot down and perceive.

Syntax:

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

Instance:

C++

#embody <iostream>

utilizing namespace std;

  

int major()

{

  

    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 comparable to strcpy(), strcmp(), and strcat() to outline strings. This technique is extra complicated and never as extensively used as the opposite two, however it may be helpful when coping with legacy code or whenever 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 major()

{

  

    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

Easy methods to Take String Enter in C++

String enter means accepting a string from a consumer. In C++. We have now various kinds of taking enter from the consumer which rely on the string. The commonest approach 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 best method 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 major() {

  

      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 major()

{

  

    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 without delay. 

Syntax:

stringstream stringstream_object(string_name);

Instance:

C++

#embody <iostream>

#embody <sstream>

#embody<string>

  

utilizing namespace std;

  

int major()

{

  

    string s = " GeeksforGeeks to the Moon ";

    stringstream obj(s);

    

    string temp;

    

    whereas (obj >> temp) {

        cout << temp << endl;

    }

    return 0;

}

Output

GeeksforGeeks
to
the
Moon

Easy methods to Go Strings to Capabilities?

In the identical approach that we go an array to a perform, strings in C++ might 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 major()

{

  

    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 applications to simulate call-by-reference in addition to to create and manipulate dynamic information buildings. Through the use of pointers we will get the primary character of the string, which is the beginning tackle of the string. As proven under, the given string might be accessed and printed via the pointers.

Instance:

C++

#embody <iostream>

utilizing namespace std;

  

int major()

{

  

    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 should 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 offers 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 needs to be allotted statically. 

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

C++ String Capabilities

C++ offers 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 seek out the dimensions 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 seek 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 just like strcpy() perform, besides that at most n bytes of src are copied
strrchr() This perform locates the final incidence of a personality within the string.
strcat() This perform appends a replica 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 simple method to modify and traverse string components. These features are:

Capabilities 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 seek out the string’s final incidence.
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 major()

{

    

    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 Capabilities

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 dimensions 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 major()

{

  

    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 might be defied in C++ utilizing character arrays and string courses. The string class offers extra superior options, whereas the character array offers primary options however is environment friendly and simple to make use of. On this article, we additionally mentioned the varied strategies to take enter from the consumer.

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

RELATED ARTICLES

Most Popular

Recent Comments