Home
Aptitude
Categories


Home » C++ STL

Create substring by given start, end index of a string | C ++ STL



In this article, we will learn how to create a substring by given start, end index of a string in C++ STL (Standard Template Library)? Here, we will use string header and its inbuilt function to implement the program.
Submitted by IncludeHelp, on August 22, 2018

Given a string, and we have to create a substring from a string, where start and end indexes are given.

To copy characters from a given start index to end index, we use substr() function, it is a library function, it is a library function of string header. It returns string object reference.

Syntax:

 string& substr(start_index, n);

Here,

  • start_index is the starting index.
  • n is the number of characters to be copied.

Example:

    Input:
    str = "C++ programming language"
    start = 2
    end = 6

    Function  call:
    str2 = substring(start, (end-start))
    //we have to access 4 characters from 2nd  index
    //thus, (end-start) = (6-2) = 4

    Output:
    str1: "C++ programming language"
    str2: "+ pr"

Program:

# include <iostream>
# include <string>

using namespace std;

int main ()
{
	//declare string and substring
	string str1 = "C++ programming language";
	string str2;

	//star and end index
	int start = 2;
	int end = 6;

	//copy charcters from 2 to 6 index
	str2 = str1.substr(start, (end - start));
	
	//print strings
	cout<< "str1: " << str1 <<endl;
	cout<< "str2: " << str2 <<endl;

	return 0;
}

Output

    str1: C++ programming language
    str2: + pr





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.