Mark As Completed Discussion

String Searching and Substring

In C++, searching for substrings in strings can be done using the find() function or by using the find() function with the string::npos constant.

The find() function returns the position of the first occurrence of the substring within the string. If the substring is not found, it returns std::string::npos.

Here's an example:

TEXT/X-C++SRC
1#include <iostream>
2#include <string>
3
4int main() {
5    std::string sentence = "Hello, world!";
6    std::string search = "world";
7
8    size_t found = sentence.find(search);
9
10    if (found != std::string::npos) {
11        std::cout << "Substring found at position: " << found << std::endl;
12    } else {
13        std::cout << "Substring not found." << std::endl;
14    }
15
16    return 0;
17}

In this example, we have a sentence that contains the substring "world". The find() function is used to search for the substring within the sentence. If the substring is found, it prints the position where the substring starts. Otherwise, it prints "Substring not found."

You can also use the rfind() function to search for the last occurrence of a substring in a string.

TEXT/X-C++SRC
1#include <iostream>
2#include <string>
3
4int main() {
5    std::string sentence = "Hello, world! Hello, everyone!";
6    std::string search = "Hello";
7
8    size_t found = sentence.rfind(search);
9
10    if (found != std::string::npos) {
11        std::cout << "Last occurrence of substring found at position: " << found << std::endl;
12    } else {
13        std::cout << "Substring not found." << std::endl;
14    }
15
16    return 0;
17}

The rfind() function searches for the last occurrence of the substring within the string.

Other functions like find_first_of(), find_last_of(), and find_first_not_of() can be used to search for specific characters or sets of characters within a string.

TEXT/X-C++SRC
1#include <iostream>
2#include <string>
3
4int main() {
5    std::string sentence = "Hello, world!";
6    std::string characters = "aeiou";
7
8    size_t found = sentence.find_first_of(characters);
9
10    if (found != std::string::npos) {
11        std::cout << "First vowel found at position: " << found << std::endl;
12    } else {
13        std::cout << "No vowel found." << std::endl;
14    }
15
16    return 0;
17}

The find_first_of() function searches for the first occurrence of any character from a set of characters within the string.

These are just some of the functions that can be used to search for substrings in strings in C++. There are many more functions available in the C++ Standard Library that provide different functionalities for manipulating strings.