1std::string str = "hello world";
2char *str = "hello world";
3char str[] = "hello world";
4char str[11] = "hello world";
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}
1#include <iostream>
2
3using namespace std;
4
5void display(char *);
6void display(string);
7
8int main()
9{
10 string str1;
11 cout << "Enter a string: ";
12 getline(cin, str1);
13 display(str1);
14 return 0;
15}
16
17
18void display(string s)
19{
20 cout << "Entered string is: " << s << endl;
21}
1#include <iostream>
2
3int main() {
4 std::cout << "Hello" << std::endl; //endl = end line/new line
5 // or
6 printf("hello");
7
8}