×

C++ STL Tutorial

C++ STL Algorithm

C++ STL Arrays

C++ STL String

C++ STL List

C++ STL Stack

C++ STL Set

C++ STL Queue

C++ STL Vector

C++ STL Map

C++ STL Multimap

C++ STL MISC.

std::string in C++ STL (Standard Template Library)

String in C++ STL (Standard Template Library): In this article, we are going to see how we can use string as a default datatype?
Submitted by Radib Kar, on February 27, 2019

String as datatype

In C, we know string basically a character array terminated by \0. Thus to operate with the string we define character array. But in C++, standard library gives us the facility to use string as a basic data type like integer.

Example

Like we define and declare,
int i=5;
    
Same way, we can do for a string like,
String s= "IncludeHelp";

Remember, a string variable (literal) need to be defined under "". 'a' is a character whereas "a" is a string.

String Operations

Basic operation that can be performed on string:

Header Files Needed

#include <string>
Or
#include <bits/stdc++.h>

C++ program to demonstrate example of std::string

#include <bits/stdc++.h>
using namespace std;

int main() {
  string s;

  // reading & printing
  cout << "Enter your string\n";
  cin >> s;
  cout << "Sting you entered is: " << s << endl;
  // printing size/length
  cout << "length of the " << s << " is = " << s.length() << endl;

  // adding two strings
  string s1 = "Include";
  string s2 = "Help";
  cout << "s1+s2: " << s1 + s2 << endl;

  // comparing
  if (s1 == s2)
    cout << s1 << " and " << s2 << " are equal" << endl;
  else
    cout << s1 << " and " << s2 << " are not equal" << endl;

  // accessing characters
  cout << "character at 0 index in " << s << " is = " << s[0] << endl;
  cout << "character at 1 index in " << s << " is = " << s[1] << endl;
  cout << "character at 5 index in " << s << " is = " << s[5] << endl;

  return 0;
}

Output

Enter your string
IncludeHelp
Sting you entered is: IncludeHelp
length of the IncludeHelp is = 11
s1+s2: IncludeHelp
Include and Help are not equal
character at 0 index in IncludeHelp is = I
character at 1 index in IncludeHelp is = n
character at 5 index in IncludeHelp is = d   

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.