« Strings in C++

Introduction to strings in C++

1#include <iostream>
2#include <iomanip>
3#include <algorithm>
4#include <string>
5#include <cstring>
6#include <vector>
7#include <cmath>
8#include <map>
9#include <climits>
10// climits for INT_MIN
11#include <unordered_map>
12using namespace std;
13int main()
14{
15 string *sp = new string;
16 // dynamic allocation of string
17
18 *sp = "India";
19 cout << "*sp: " << *sp << endl;
20 cout << "sp: " << sp << endl;
21
22 string s = "abc";
23 // static allocation of string
24
25 // cin >> s;
26 // I Love India will fail here as space is there. cin breaks around space
27
28 getline(cin, s);
29 cout << s << endl;
30
31 s = "Geek Convert";
32 cout << s << endl;
33 s[0] = 'r';
34 // strings can be treated as array. We can replace its char by char
35
36 cout << s << endl;
37
38 string s1 = "abc";
39 cout << s1 << endl;
40
41 string s2 = s + s1;
42 // we can concatenate strings
43
44 cout << s2 << endl;
45
46 cout << s2.size() << endl;
47 cout << s2.length() << endl;
48
49 cout << s2.substr(10) << endl;
50 // gets everything after 10
51
52 cout << s2.substr(10, 3) << endl;
53 // gets everything after 10 but only length 3
54
55 cout << s2.find("ek") << endl; // returns position for the first occurrence of an in the string s2
56
57 return 0;
58}