string c++ declare code example

Example 1: declaring strings c++

std::string str = "hello world"; 
char *str = "hello world";
char str[] = "hello world"; 
char str[11] = "hello world";

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: c++ strings

#include <iostream>

using namespace std;

void display(char *);
void display(string);

int main()
{
    string str1;
    cout << "Enter a string: ";
    getline(cin, str1);
    display(str1);
    return 0;
}


void display(string s)
{
    cout << "Entered string is: " << s << endl;
}

Tags:

Cpp Example