Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • C++
  • Standard Template Library
  • STL Vector
  • STL List
  • STL Set
  • STL Map
  • STL Stack
  • STL Queue
  • STL Priority Queue
  • STL Interview Questions
  • STL Cheatsheet
  • C++ Templates
  • C++ Functors
  • C++ Iterators
Open In App
Next Article:
std::basic_string::at in C++
Next article icon

std::string::assign() in C++

Last Updated : 28 Oct, 2020
Comments
Improve
Suggest changes
Like Article
Like
Report

The member function assign() is used for the assignments, it assigns a new value to the string, replacing its current contents. 
Syntax 1: Assign the value of string str. 

string& string::assign (const string& str)  str :  is the string to be assigned. Returns : *this 
CPP
// CPP code for assign (const string& str) #include <iostream> #include <string> using namespace std;   // Function to demonstrate assign void assignDemo(string str1, string str2) {     // Assigns str2 to str1     str1.assign(str2);     cout << "After assign() : ";     cout << str1;  }          // Driver code int main() {     string str1("Hello World!");     string str2("GeeksforGeeks");      cout << "Original String : " << str1 << endl;     assignDemo(str1, str2);       return 0; } 

Output: 

Original String : Hello World! After assign() : GeeksforGeeks

Syntax 2: Assigns at most str_num characters of str starting with index str_idx. It throws out_of _range if str_idx > str. size(). 

string& string::assign (const string& str, size_type str_idx, size_type str_num)  str : is the string to be assigned. str_idx : is the index number in str. str_num : is the number of characters picked  from str_idx to assign Return : *this 
CPP
// CPP code to illustrate // assign(const string& str, size_type  // str_idx, size_type str_num)   #include <iostream> #include <string> using namespace std;   // Function to demonstrate assign void assignDemo(string str1, string str2) {     // Assigns 8 characters from     // 5th index of str2 to str1     str1.assign(str2, 5, 8);     cout << "After assign() : ";     cout << str1;  }          // Driver code int main() {     string str1("Hello World!");     string str2("GeeksforGeeks");      cout << "Original String : " << str1 << endl;     assignDemo(str1, str2);       return 0; } 

Output: 

Original String : Hello World! After assign() : forGeeks 

Syntax 3: Assign the characters of the C-string cstr. It throws length_error if the resulting size exceeds the maximum number of characters. 

string & string::assign (const char* cstr)  Assigns all characters of cstr up to but not including '\0'. Returns : *this. Note : that cstr may not be a null pointer (NULL). 
CPP
// CPP code for assign (const char* cstr)   #include <iostream> #include <string> using namespace std;   // Function to demonstrate assign void assignDemo(string str) {     // Assigns GeeksforGeeks to str     str.assign("GeeksforGeeks");     cout << "After assign() : ";     cout << str;  }          // Driver code int main() {     string str("Hello World!");      cout << "Original String : " << str << endl;     assignDemo(str);       return 0; } 

Output: 

Original String : Hello World! After assign() : GeeksforGeeks 

Syntax 4: Assigns chars_len characters of the character array chars. It throws length_error if the resulting size exceeds the maximum number of characters. 

string& string::assign (const char* chars, size_type chars_len)  *chars : is the pointer to the array to be assigned. chars_len : is the number of characters to be assigned from  character array. Note : that chars must have at least chars_len characters. Returns : *this. 
CPP
// CPP code to illustrate  // string& string::assign  // (const char* chars, size_type chars_len)   #include <iostream> #include <string> using namespace std;   // Function to demonstrate assign void assignDemo(string str) {     // Assigns first 5 characters of     // GeeksforGeeks to str     str.assign("GeeksforGeeks", 5);     cout << "After assign() : ";     cout << str;  }          // Driver code int main() {     string str("Hello World!");      cout << "Original String : " << str << endl;     assignDemo(str);       return 0; } 

Output: 

Original String : Hello World! After assign() : Geeks 

Syntax 5: Assigns num occurrences of character c. It throws length_error if num is equal to string::npos 

string & string::assign (size_type num, char c)  num :  is the number of occurrences to be assigned. c :  is the character which is to be assigned repeatedly.  Throws length_error if the resulting size exceeds the maximum number(max_size) of characters. Returns : *this. 
CPP
// CPP code for string&  // string::assign (size_type num, char c)   #include <iostream> #include <string> using namespace std;   // Function to demonstrate assign void assignDemo(string str) {     // Assigns 10 occurrences of 'x'     // to str     str.assign(10, 'x');     cout << "After assign() : ";     cout << str;  }          // Driver code int main() {     string str("#########");      cout << "Original String : " << str << endl;     assignDemo(str);       return 0; } 

Output: 

Original String : ######### After assign() : xxxxxxxxxx 

Syntax 6: Assigns all characters of the range [beg, end). It throws length_error if range outruns the actual content of string. 

template <class InputIterator>    string& assign (InputIterator first, InputIterator last) first, last : Input iterators to the initial and final positions  in a sequence.  Returns : *this. 
CPP
// CPP code for string&  // string::assign (size_type num, char c)   #include <iostream> #include <string> using namespace std;   // Function to demonstrate assign void assignDemo(string str) {     string str1;          // Assigns all characters between     // str.begin()+6 and str.end()-0 to str1     str1.assign(str.begin()+6, str.end()-0);     cout << "After assign() : ";     cout << str1;  }          // Driver code int main() {     string str("Hello World!");      cout << "Original String : " << str << endl;     assignDemo(str);       return 0; } 

Output: 

Original String : Hello World! After assign() : World! 

If you like GeeksforGeeks(We know you do!) and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected].


Next Article
std::basic_string::at in C++

S

Sakshi Tiwari
Improve
Article Tags :
  • Misc
  • C++
  • STL
  • cpp-string
  • cpp-strings-library
Practice Tags :
  • CPP
  • Misc
  • STL

Similar Reads

  • std::basic_string::at in C++
    Returns a reference to the character at the specified location pos. The function automatically checks whether pos is the valid position of a character in the string (i.e., whether pos is less than the string length), throwing an out_of_range exception if it is not. Syntax: reference at (size_type po
    1 min read
  • std::string::append() in C++
    The string::append() in C++ is used append the characters or the string at the end of the string. It is the member function of std::string class . The string::append() function can be used to do the following append operations: Table of Content Append a Whole StringAppend a Part of the StringAppend
    3 min read
  • std::string class in C++
    C++ has in its definition a way to represent a sequence of characters as an object of the class. This class is called std:: string. The string class stores the characters as a sequence of bytes with the functionality of allowing access to the single-byte character. String vs Character ArrayString Ch
    8 min read
  • Vector assign() in C++ STL
    In C++, the vector assign() is a built-in method used to assign the new values to the given vector by replacing old ones. It also modifies the size of the vector according to the given number of elements. Let’s take a look at an example that shows the how to use this function. [GFGTABS] C++ #include
    4 min read
  • std::to_string in C++
    In C++, the std::to_string function is used to convert numerical values into the string. It is defined inside <string> header and provides a simple and convenient way to convert numbers of any type to strings. In this article, we will learn how to use std::to_string() in C++. Syntaxstd::to_str
    1 min read
  • std::string::clear in C++
    The string content is set to an empty string, erasing any previous content and thus leaving its size at 0 characters. Parameters: none Return Value: none void string ::clear () - Removes all characters (makes string empty) - Doesn't throw any error - Receives no parameters and returns nothing // CPP
    1 min read
  • std::string::insert() in C++
    In C++, the string::insert() function is used insert the characters or a string at the given position of the string. It is the member function of std::string class. The string::insert method can be used in the following ways to: Table of Content Insert a Single CharacterInsert a Single Character Mul
    4 min read
  • std::basic_string::operator[] in C++
    Returns a reference to the character at specified location pos. No bounds checking is performed. If pos > size(), the behavior is undefined. Syntax : reference operator[] (size_type pos); const_reference operator[] (size_type pos) const; Parameters : pos - position of the character to return Retu
    1 min read
  • std::basic_string::max_size in C++
    std::basic_string::max_size is used to compute the maximum number of elements the string is able to hold due to system or library implementation limitations. size_type max_size() const; Parameters : None Return value : Maximum number of characters Exceptions : None // CPP program to compute the limi
    1 min read
  • std::string::push_back() in C++
    The std::string::push_back() method in C++ is used to append a single character at the end of string. It is the member function of std::string class defined inside <string> header file. In this article, we will learn about std::string::push_back() method in C++. Example: [GFGTABS] C++ // C++ P
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences