C++ Substring - Tutorial Kart

C++ Substring

C++ Substring

To find the substring in a string, you can use substr() function, or use a looping technique to find the substring

yourself.

In this tutorial, we go through some of the processes to find a substring of a given string, given a starting

position, length or an ending position.

Syntax of substr() function

substr() is a member function of string class. Following is the syntax of substr() function.

substr (pos, len)

substr() function is called on a string object.

pos is the starting position or index of substring in this string.

len is the number of characters in the substring.

The default value of pos is zero. If pos is not specified, then the whole string is returned as substring.

len is optional. If len is not specified, the substring till the end of this string is returned.

substr() returns a newly formed string object representing the substring formed using this string, pos

and len .

Example ¨C substr() ¨C Find Substring with start position and length

In this example, we take a string with some initial value and find the substring of this string starting at given

starting position and spanning a specified length.

C++ Program

#include

using namespace std;

int main() {

string str1 = "We are changing the world.";

int pos = 5;

int len = 10;

string substring = str1.substr(pos, len);

cout ................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download