1// For C++11 and later versions
2string str1 = "45";
3string str2 = "3.14159";
4string str3 = "31337 geek";
5
6int myint1 = stoi(str1);
7int myint2 = stoi(str2);
8int myint3 = stoi(str3);
9
10// Output
11stoi("45") is 45
12stoi("3.14159") is 3
13stoi("31337 geek") is 31337
1// Include the string library
2#include <string>
3
4// Create a string variable
5string greeting = "Hello";
1#include <string>
2#include <iostream>
3#include <type_traits>
4#include <cstring>
5
6int main() {
7 std::string str = "Hello, there";
8 std::cout << std::boolalpha
9 << str.capacity() << ", " << str.size() << ", " << std::strlen(str.data()) // 12, 12, 12
10 << '\n' << std::is_same_v<std::string, std::basic_string<char>> // true
11 << '\n' << str.front() + str.substr(1, 10) + str.back() // Hello there
12 << '\n' << str[0] // H
13 << '\n';
14
15 str += "!";
16 std::cout << str << '\n'; // Hello, there!
17 str.erase(4, 4); // Hellhere!
18 str.pop_back(); // Hellhere
19 str.insert(4, " "); // Hell here
20 std::cout << str << '\n'; // Hell here
21
22}
1#include <iostream>
2#include <string>//for printing std::string
3int main()
4
5{
6 //A string is a group of characters and an array of const chars
7 const char* name = "Caleb";//C style string
8 //how string actually works below:
9 //String without null terminating character below:
10
11 char name2[5] = { 'C','a','l','e','b' };// string is just an array of characters
12 //The above doesn't have an null termination character at the end cout will not now where the string ends and will acess memory that is not a part of your string
13 std::cout << name2 << std::endl;//output => Caleb + somejunk //this is because null terminating char is not present at the end of array
14 //String with null terminating character below:
15
16 char name3[6] = { 'C','a','l','e','b','\0' };//null terminating char '\0' or '0' can be used
17 std::cout << name3 << std::endl;//output => Caleb // because null terminating char is present cout knows where array ends
18
19 //std::string class in c++ is takes an array of const chars and a bunch of functions to manuplate it:
20 //std::string has a constructor that takes const char array
21 std::string name4 = "Caleb";
22 name4.size();//gives size of string and there are many more methods in std::string class
23
24 //appending to std::string
25
26 //"Ever thing inside these double quotes becomes const char array"
27 //std::string namee = "Caleb" +"Hello";//This will give error because adding const char array to const char array
28 std::string namee = "Caleb";
29 namee += " Hello";//This will work because adding a ptr to a actual string
30 std::cout << namee << std::endl;
31//You can also use the below
32 std::string namee2 = std::string("Caleb")+" Hello";// This will work because constructor will convert const char array to string, adding a ptr to string
33 std::cout << namee2 << std::endl;
34 std::cin.get();
35
36}