CodeBlanks Logo Icon CodeBlanks

contains and indexOf

Learn search with contains and indexOf.

contains and indexOf

To ask whether a substring exists inside a String you use the .contains() method: "welcome".contains("come") evaluates to true. The return type is bool; either true or false.

If you want the position of the substring you use .indexOf(): "welcome".indexOf("come") returns 3. Indexing is zero-based. If the substring is not found .indexOf() returns -1.

-1 when not found

When the substring is not found .indexOf() returns -1. This value is often used to check whether a substring exists: if (email.indexOf("@") != -1) roughly tests whether a text might be an email.

A more readable way is to use .contains(): if (email.contains("@")). Both forms give the same result; .contains() is clearer. Practical rule: use .contains() for existence, .indexOf() for position.

Practice Find the @ index

Declare a String variable email with the value "alex@dart.com". Declare a new variable at and assign the result of email.indexOf("@") to it. Then print at with print(at);. The output on a single line must be 4.

Starter code

main.dart
// Declare email, assign the @ index to at via indexOf, print it

Sample solution

main.dart
String email = "alex@dart.com";
var at = email.indexOf("@");
print(at);

Expected output

4

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What does "welcome".contains("come") return?

main.dart
"welcome".contains("come")
  • true Correct answer
  • false
  • 3
  • -1

Explanation: "come" exists inside "welcome"; the result is true.

2 Match each method to its job

Term Meaning
contains(x) Exists (bool)
indexOf(x) First index (-1 if absent)
substring(0, 3) Takes a part
.length Character count

3 Write the indexOf call

Question
String email = "a@b.com";
print(email____);
Answer
String email = "a@b.com";
print(email.indexOf("@"));

Explanation: .indexOf("@") gives the index of the @ sign.

All lessons in Beginner