string at c++ code example

Example 1: string in cpp

// Include the string library
#include <string>

// Create a string variable
string greeting = "Hello";

Example 2: c++ string

#include <string>

std::string myString = "Hello, World!";

Example 3: c++ string

#include <string>
#include <iostream>
#include <type_traits>
#include <cstring>

int main() {
  std::string str = "Hello, there";
  std::cout << std::boolalpha
  << str.capacity() << ", " << str.size() << ", " << std::strlen(str.data()) // 12, 12, 12
  << '\n' << std::is_same_v<std::string, std::basic_string<char>> // true
  << '\n' << str.front() + str.substr(1, 10) + str.back() // Hello there
  << '\n' << str[0] // H
  << '\n';
  
  str += "!"; 
  std::cout << str << '\n'; // Hello, there!
  str.erase(4, 4); // Hellhere!
  str.pop_back(); // Hellhere
  str.insert(4, " "); // Hell here
  std::cout << str << '\n'; // Hell here
  
}

Example 4: string in cpp

// you want to include <string>
#include <string>
#include <iostream>

int main() 
{
  string helloWorld = "Hello World!"; // creating string and assigning
  std::cout << helloWorld;            // will output what you assigned it!
                                      /* you can also use strings with user 
                                      input (cin/getline)*/
  string namePerson{};
  getline(cin, namePerson); // getline allows for multi word input
  std::cout << namePerson;  // outputs name which person inputted
}

Example 5: how to access the element of string in c++

string myString = "Hello";
cout << myString[0];
// Outputs H

Tags:

Cpp Example