insert in strings cpp code example
Example 1: string insert c++
// inserting into a string
#include <iostream>
#include <string>
int main ()
{
std::string str="to be question";
std::string str2="the ";
std::string str3="or not to be";
std::string::iterator it;
// used in the same order as described above:
str.insert(6,str2); // to be (the )question
str.insert(6,str3,3,4); // to be (not )the question
str.insert(10,"that is cool",8); // to be not (that is )the question
str.insert(10,"to be "); // to be not (to be )that is the question
str.insert(15,1,':'); // to be not to be(:) that is the question
it = str.insert(str.begin()+5,','); // to be(,) not to be: that is the question
str.insert (str.end(),3,'.'); // to be, not to be: that is the question(...)
str.insert (it+2,str3.begin(),str3.begin()+3); // (or )
std::cout << str << '\n';
return 0;
}
Example 2: appending string in c++
#include<iostream>
#include <string>
int main() {
//"Ever thing inside these double quotes becomes const char array"
// std::string namee = "Caleb" +"Hello";//This will give error because adding const char array to const char array
std::string namee = "Caleb";
namee += " Hello";//This will work because adding a ptr to a actual string
std::cout << namee << std::endl;// output=>Caleb Hello
//You can also use the below
std::string namee2 = std::string("Caleb")+" Hello";// This will work because constructor will convert const char array to string, adding a ptr to string
std::cout << namee2 << std::endl;// output=>Caleb Hello
std::cin.get();
}