string operations c++ code example
Example 1: string in cpp
#include <string>
string greeting = "Hello";
Example 2: declaring strings c++
std::string str = "hello world";
char *str = "hello world";
char str[] = "hello world";
char str[11] = "hello world";
Example 3: c++ string
#include <string>
std::string myString = "Hello, World!";
Example 4: 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())
<< '\n' << std::is_same_v<std::string, std::basic_string<char>>
<< '\n' << str.front() + str.substr(1, 10) + str.back()
<< '\n' << str[0]
<< '\n';
str += "!";
std::cout << str << '\n';
str.erase(4, 4);
str.pop_back();
str.insert(4, " ");
std::cout << str << '\n';
}
Example 5: string in c++
#include <iostream>
#include <string>
int main()
{
const char* name = "Caleb";
char name2[5] = { 'C','a','l','e','b' };
std::cout << name2 << std::endl;
char name3[6] = { 'C','a','l','e','b','\0' };
std::cout << name3 << std::endl;
std::string name4 = "Caleb";
name4.size();
std::string namee = "Caleb";
namee += " Hello";
std::cout << namee << std::endl;
std::string namee2 = std::string("Caleb")+" Hello";
std::cout << namee2 << std::endl;
std::cin.get();
}
Example 6: 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;
}