Dart String compareTo()
Syntax & Examples


Syntax of String.compareTo()

The syntax of String.compareTo() method is:

 int compareTo(String other) 

This compareTo() method of String compares this string to other.

Parameters

ParameterOptional/RequiredDescription
otherrequiredthe pattern to search for within the string

Return Type

String.compareTo() returns value of type int.



✐ Examples

1 Check if "world" is in the string

In this example,

  1. We create a string str with the value 'Hello, world!'.
  2. We then use the contains() method to check if "world" is present in the string.
  3. We print the result to standard output.

Dart Program

void main() {
  String str = 'Hello, world!';
  bool containsWorld = str.contains('world');
  print('Contains "world" in str: $containsWorld');
}

Output

Contains "world" in str: true

2 Check if "D" is in the string

In this example,

  1. We create a string str with the value 'ABCDEF'.
  2. We then use the contains() method to check if 'D' is present in the string.
  3. We print the result to standard output.

Dart Program

void main() {
  String str = 'ABCDEF';
  bool containsD = str.contains('D');
  print('Contains "D" in str: $containsD');
}

Output

Contains "D" in str: true

3 Check if "ipsum" is in the string

In this example,

  1. We create a string str with the value 'Lorem ipsum dolor sit amet'.
  2. We then use the contains() method to check if 'ipsum' is present in the string.
  3. We print the result to standard output.

Dart Program

void main() {
  String str = 'Lorem ipsum dolor sit amet';
  bool containsIpsum = str.contains('ipsum');
  print('Contains "ipsum" in str: $containsIpsum');
}

Output

Contains "ipsum" in str: true

Summary

In this Dart tutorial, we learned about compareTo() method of String: the syntax and few working examples with output and detailed explanation for each example.