Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Вивчайте Challenge: Searching Within Strings | Text Data Type
Practice
Projects
Quizzes & Challenges
Quizzes
Challenges
/
C++ Data Types

bookChallenge: Searching Within Strings

Method find()

Sometimes, you may need to search for specific text within a string. This can be done using the .find() or .rfind() methods. Let’s begin with the .find() method.

find.h

find.h

copy
1
str.find("text to find")

It returns the index of the first character of the first match.

main.cpp

main.cpp

copy
1234567
#include <iostream> int main() { std::string str = "codecodefinity"; std::cout << str.find("code") << std::endl; // (code)codefinity }

You can also specify the position of the first character in the string to be considered in the search. It can be done using the pos argument. Any characters before the pos index are ignored in a search.

Here is an example of finding the first "code" starting from a 3-rd character.

main.cpp

main.cpp

copy
1234567
#include <iostream> int main() { std::string str = "codecodefinity"; std::cout << str.find("code", 3) << std::endl; // __de(code)finity }

Method rfind()

You can also locate the last occurrence of some text using the .rfind() method.

rfind.h

rfind.h

copy
1
str.rfind("text to find")

While .find() retrieves the first occurrence of text, .rfind() finds the last occurrence and stands for reverse find.

main.cpp

main.cpp

copy
12345678
#include <iostream> int main() { std::string str = "codecodefinity"; std::cout << str.find("code") << std::endl; std::cout << str.rfind("code") << std::endl; }
Note
Note

When .find() or .rfind() cannot locate the substring, they return string::npos. This is a numeric constant that represents an invalid position. It is stored as the largest possible size_t value, which makes it easy to detect failed searches.

main.cpp

main.cpp

copy
12345678
#include <iostream> int main() { std::string str = "codecodefinity"; std::cout << str.rfind("abc") << std::endl; std::cout << std::string::npos << std::endl; }
Завдання

Swipe to start coding

You are building a simple email filter. Your goal is to allow users to register with any email and mark emails from codefinity.com as allowed.

The function isAllowedEmail takes an email as string.

  1. Use rfind() to find the last '@' symbol in the email.
  2. Compare the result of rfind with -1 to check if the '@' symbol exists. If no '@' is found, return false because the email is invalid.
  3. Initialize a string variable domain as an empty string.
  4. Use a for loop starting from atPos + 1 up to the length of email to iterate over characters after the '@'.
  5. In each iteration, append the character to the domain variable.
  6. If domain equals "codefinity.com", return true. Otherwise, return false.

Рішення

Все було зрозуміло?

Як ми можемо покращити це?

Дякуємо за ваш відгук!

Секція 3. Розділ 6
single

single

Запитати АІ

expand

Запитати АІ

ChatGPT

Запитайте про що завгодно або спробуйте одне із запропонованих запитань, щоб почати наш чат

Suggested prompts:

What is the difference between .find() and .rfind()?

Can you show an example of using the pos argument with .find()?

How does .find() behave if the substring is not found?

close

bookChallenge: Searching Within Strings

Свайпніть щоб показати меню

Method find()

Sometimes, you may need to search for specific text within a string. This can be done using the .find() or .rfind() methods. Let’s begin with the .find() method.

find.h

find.h

copy
1
str.find("text to find")

It returns the index of the first character of the first match.

main.cpp

main.cpp

copy
1234567
#include <iostream> int main() { std::string str = "codecodefinity"; std::cout << str.find("code") << std::endl; // (code)codefinity }

You can also specify the position of the first character in the string to be considered in the search. It can be done using the pos argument. Any characters before the pos index are ignored in a search.

Here is an example of finding the first "code" starting from a 3-rd character.

main.cpp

main.cpp

copy
1234567
#include <iostream> int main() { std::string str = "codecodefinity"; std::cout << str.find("code", 3) << std::endl; // __de(code)finity }

Method rfind()

You can also locate the last occurrence of some text using the .rfind() method.

rfind.h

rfind.h

copy
1
str.rfind("text to find")

While .find() retrieves the first occurrence of text, .rfind() finds the last occurrence and stands for reverse find.

main.cpp

main.cpp

copy
12345678
#include <iostream> int main() { std::string str = "codecodefinity"; std::cout << str.find("code") << std::endl; std::cout << str.rfind("code") << std::endl; }
Note
Note

When .find() or .rfind() cannot locate the substring, they return string::npos. This is a numeric constant that represents an invalid position. It is stored as the largest possible size_t value, which makes it easy to detect failed searches.

main.cpp

main.cpp

copy
12345678
#include <iostream> int main() { std::string str = "codecodefinity"; std::cout << str.rfind("abc") << std::endl; std::cout << std::string::npos << std::endl; }
Завдання

Swipe to start coding

You are building a simple email filter. Your goal is to allow users to register with any email and mark emails from codefinity.com as allowed.

The function isAllowedEmail takes an email as string.

  1. Use rfind() to find the last '@' symbol in the email.
  2. Compare the result of rfind with -1 to check if the '@' symbol exists. If no '@' is found, return false because the email is invalid.
  3. Initialize a string variable domain as an empty string.
  4. Use a for loop starting from atPos + 1 up to the length of email to iterate over characters after the '@'.
  5. In each iteration, append the character to the domain variable.
  6. If domain equals "codefinity.com", return true. Otherwise, return false.

Рішення

Switch to desktopПерейдіть на комп'ютер для реальної практикиПродовжуйте з того місця, де ви зупинились, використовуючи один з наведених нижче варіантів
Все було зрозуміло?

Як ми можемо покращити це?

Дякуємо за ваш відгук!

Секція 3. Розділ 6
single

single

some-alt