×

C++ STL Tutorial

C++ STL Algorithm

C++ STL Arrays

C++ STL String

C++ STL List

C++ STL Stack

C++ STL Set

C++ STL Queue

C++ STL Vector

C++ STL Map

C++ STL Multimap

C++ STL MISC.

string::assign() function with Example | C++ STL

string::assign() function with Example in C++ STL (Standard Template Library): In this article, we are going to learn String::assign() function with Example in C++ STL.
Submitted by IncludeHelp, on August 19, 2018

C++ STL - string::assign() Function

assign()
is a library function of "string" class and it is used to assign, replace the string. This function is overloaded function, we can use it for many purposes i.e. to assign the string, replace a part of the string, any constant value etc.

Ref: std::string::assign()

Usage and Syntaxes

1) To assign string with another string object (Complete string)

 string& string.assign (const string& str);

2) To assign string with another string object/ substring, starting by subpos index to sublen characters

 string& string.assign (const string& str, size_t subpos, size_t sublen);

3) To assign string with another constant string

 string& string.assign (const char* s);

4) To assign string with n characters of another constant string

 string& string.assign (const char* s, size_t n);

5) To assign string with the character 'c', n times

 string& string.assign (size_t n, char c);

Example

#include <iostream>
#include <string>
using namespace std;

int main() {
  // declare string
  string str = "Hello world, how are you?";
  string str1;

  // assign complete string (str) to str1
  str1.assign(str);
  cout << "str1: " << str1 << endl;

  // assign first 11 characters from str to the str1
  str1.assign(str, 0, 11);
  cout << "str1: " << str1 << endl;

  // assign 3 characters from index 4 of str to the str1
  str1.assign(str, 4, 3);
  cout << "str1: " << str1 << endl;

  // assign complete string by using
  // str.begin () and str.end () functions
  str1.assign(str.begin(), str.end());
  cout << "str1: " << str1 << endl;

  // assign a part of the string by using
  // str.begin () and str.end () functions
  str1.assign(str.begin() + 6, str.end() - 2);
  cout << "str1: " << str1 << endl;

  // assign 3 characters of a constant string
  str1.assign("Hello", 3);
  cout << "str1: " << str1 << endl;

  return 0;
}

Output

str1: Hello world, how are you?
str1: Hello world
str1: o w
str1: Hello world, how are you?
str1: world, how are yo
str1: Hel

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.