String Methods in Dart Programming

Dart ProgrammingServer Side ProgrammingProgramming

String class in Dart contains different methods that we use to make working with strings easier and more expressive.

There are many methods present in the String class, some of the common ones are −

  • contains(Pattern<>)

  • trim()

  • toLowerCase()

  • toUpperCase()

  • split(Pattern)

  • compareTo(another string)

We will explore each of the above string methods in this article.

contains() method

The contains() method is used to find a pattern present in the string or not. If the pattern that we are searching is present in the string, then the contains() method returns true, else it returns false.

Example

Consider the example shown below −

 Live Demo

void main(){
   String name = " Tutorials Point ";
   print(name.contains("Point"));
   print(name.contains("Sample"));
}

In the above example, we are using the contains() method on the variable name, and inside the two calls to the contains() method, we passed two string patterns, one is present in the string, and the other isn't.

Output

true
false

trim() method

The trim() method is used to remove any trailing spaces present in the string. It removes the trailing spaces from both the starting position and the ending position.

Example

Consider the example shown below −

 Live Demo

void main(){
   String name = " Tutorials Point ";
   print(name.trim());
}

Output

Tutorials Point

toLowerCase() method

The toLowerCase() method on string is used to convert the given string characters or letters to all in lower cases.

Example

Consider the example shown below −

 Live Demo

void main(){
   String name = "Tutorials Point";
   print(name.toLowerCase());
}

Output

tutorials point

toUpperCase() method

The toUpperCase() method on string is used to convert the given string characters or letters to all in upper cases.

Example

Consider the example shown below −

 Live Demo

void main(){
   String name = "Tutorials Point";
   print(name.toUpperCase());
}

Output

TUTORIALS POINT

split() method

The split method of string class, takes a pattern as an argument and it splits that string based on the provided pattern.

Example

Consider the example shown below −

 Live Demo

void main(){
   String name = "Tutorials Point";
   print(name.split(" "));
}

In the above example, we are splitting the string on the basis of an empty string.

Output

[Tutorials, Point]

compareTo() method

The compareTo() method is used to compare two strings, and it returns an integer value. It returns 1, if the string comes after the other string in lexicographically sequence, -1 is before and 0 if they are the same.

Example

Consider the example shown below −

 Live Demo

void main(){
   String name = "Tutorials Point";
   print(name.compareTo("Random Point"));
   print(name.compareTo("Tutorials Point"));
}

Output

1
0
raja
Published on 24-May-2021 12:02:49
Advertisements