Dart program to find substring in a string

Dart program to find substring in a string:

This post will show you how to find substring in a string in dart. We will read the string and indices as inputs from the user and prints out the substring in that index range.

substrin method:

substring() is defined in the String class of dart. It finds a substring in a given range. Below is the definition of this method:

String.substring(start [,end])

It finds a substring in the range of start and end index of the string, including the start index and excluding end. end is optional. If we don’t give it, it will consider to the end of the string starting from start.

For example:

import 'dart:io';

void main() {
  print("Enter the string : ");
  String givenStr = stdin.readLineSync();

  print("Enter the first index : ");
  int first = int.parse(stdin.readLineSync());

  print("Enter the last index :");
  int last = int.parse(stdin.readLineSync());

  print(givenStr.substring(first, last + 1));
}

Here, we are taking the strings as inputs from the user. The string is stored in givenStr variable. The first and last index of the required substring are stored in first and last integer variables. The last print statement is used to print the substring in the string from character at index start to the character at index last. We are passing last + 1 as the second argument to substring.

Output:

It prints outputs as like below:

Enter the string : 
hello world
Enter the first index : 
6
Enter the last index :
10
world

dart find substring in string

Exception:

Note that it will throw one excepion if we give invalid value. The exception is RangeError:

Enter the string : 
hello world
Enter the first index : 
0
Enter the last index :
100
Unhandled exception:
RangeError: Value not in range: 101
#0      _StringBase.substring (dart:core-patch/string_patch.dart:389:7)

Handling the exception:

We can simply use a try-catch block to handle this RangeError :

import 'dart:io';

void main() {
  print("Enter the string : ");
  String givenStr = stdin.readLineSync();

  print("Enter the first index : ");
  int first = int.parse(stdin.readLineSync());

  print("Enter the last index :");
  int last = int.parse(stdin.readLineSync());

  try {
    print(givenStr.substring(first, last + 1));
  } on RangeError {
    print("Invalid inputs !!");
  }
}

Invalid input results:

Enter the string : 
hello world
Enter the first index : 
0
Enter the last index :
100
Invalid inputs !!

Enter the string : 
hello world
Enter the first index : 
-1
Enter the last index :
10
Invalid inputs !!

You might also like: