Dart program to check if a string ends or starts with a substring

Published by admin on

Dart check if a string ends or starts with a substring

Introduction :

In this dart tutorial, we will learn how to check if a string is ending with or starting with a substring. Our program will ask the user to enter a string first. It will again ask the user to enter a substring. It will print out the result if the substring is found at the end or start of the string.

 

startsWith and endsWith :

We are using the following two methods in this example :

1. startsWith(Pattern p, [ int i = 0 ]) → bool :

This method is used to check if a string starts with another substring or pattern or not. Optionally, it takes one second parameter i to define the start point. It returns one boolean value.

2. endsWith(String s) → bool :

This method is used to check if a string ends with another substring or not. It returns one boolean value defining the string ends with the substring or not.

 

Dart program :

The final program looks like as below :

import 'dart:io';

void main() {
  String mainString;
  String subString;

  print("Enter a string : ");
  mainString = stdin.readLineSync();

  print("Enter the sub string : ");
  subString = stdin.readLineSync();

  if (mainString.startsWith(subString)) {
    print('"$mainString" starts with "$subString"');
  } else if (mainString.endsWith(subString)) {
    print('"$mainString" ends with "$subString"');
  } else {
    print('"$mainString" doesn\'t contain "$subString"');
  }
}

 

Sample Output :

Enter a string :
hello world
Enter the sub string :
hello
hello world" starts with "hello"

Enter a string :
hello world
Enter the sub string :
world
hello world" ends with "world"

Enter a string :
hello world
Enter the sub string :
universe

 

Explanation :

In this example, we are using one if-elseif-else condition to check if a string starts or ends with a given substring. We are using the startsWith and endsWith methods as defined above. The if statement checks if the string starts with a substring, the else-if statement checks if the string ends with the substring and the else statement runs if both if and else statements fails.

dart string startswith endswith

Categories: dart

0 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *