C++ tutorial-assign() function

C++ String Manipulation

C++ assign() function

The assign() function is used to assign all characters of a string to another string or just part of a string to another string. Normally, you can assign one string to another by using assignment operator(=). However, if you want to assign a proportion of a string to another string you need to you the assign() function instead. The assign() function has two forms. The first form is to assign all characters from a string to another and the second form assigns part of a string to another string.


assign(string, start, num_chars);

The second form of the assign() function accepts three arguments. The first argument is a string that you want to cut part of it and the start argument indicates where you want to start cutting. The num_chars argument is about the number of characters that you want to cut.


#include <cstdlib>
#include <iostream>
#include <conio.h>

using namespace std;

void strmanip(){

  string str1;
  string str2="C++ programming code";
  str1.assign(str2);//assign entire string str2 to another string str1
  str1.assign(str2,4,11);//assign part of string str 2 to another string str1


int main(){

  return 0;



This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages:
C, C++, C#, Java, VB.NET, Python, VBA,PHP & Mysql, SQL, JSP, ASP.NET,HTML, CSS, JQuery, JavaScript and other applications such as MS Excel, MS Access, and MS Word. However, we don't guarantee all things of the web are accurate. If you find any error, please report it then we will take actions to correct it as soon as possible.