C++ Online Compiler
Example: Finding and Extracting Substrings
C
C++
C#
Java
Python
PHP
main.cpp
STDIN
Run
// Finding and Extracting Substrings #include
#include
using namespace std; int main() { // Step 1: Declare a source string string sentence = "The quick brown fox jumps over the lazy dog."; // Step 2: Find the position of a substring string searchWord = "fox"; size_t foundPos = sentence.find(searchWord); // size_t is an unsigned type if (foundPos != string::npos) { // string::npos indicates not found cout << "'" << searchWord << "' found at position: " << foundPos << endl; // Step 3: Extract a substring starting from the found position // Syntax: substr(start_index, length) string extractedWord = sentence.substr(foundPos, searchWord.length()); cout << "Extracted word: " << extractedWord << endl; // Step 4: Extract a substring from a specific point to the end string restOfString = sentence.substr(foundPos); cout << "Rest of the string from 'fox': " << restOfString << endl; // Step 5: Extract a specific range (e.g., "quick brown") size_t startQ = sentence.find("quick"); string quickBrown = sentence.substr(startQ, 11); // "quick brown" has 11 chars cout << "Extracted 'quick brown': " << quickBrown << endl; } else { cout << "'" << searchWord << "' not found." << endl; } return 0; }
Output
Clear
ADVERTISEMENTS