Dart program to remove the last character of a string

Published by admin on

Introduction :

In this post, I will show you how to remove the last character of a string in dart. We have two different ways to do that using the standard Dart libraries. The example programs will take the string as input from the user, remove the last character and print out the result string.

 

Method 1: Using substring :

substring method of dart string class is defined as below :

String substring(int startIndex, [int endIndex]);

It takes two parameters, start and the end index for the result string. It returns the substring starting from startIndex inclusive and ending at endIndex exclusive.

We can remove the last character of a string using this method by providing the start index as 0 and end index as string-length – 1.

For example, if the string is hello and if we pass the start index as 0 and end index as 4, it will return hell.

import 'dart:io';

main() {
  print("Enter a string : ");
  var userInput = stdin.readLineSync();
  print(userInput.substring(0, userInput.length - 1));
}

 

Sample output :

Enter a string : 
hello
hell

Enter a string : 
hello world
hello worl

Enter a string : 
hello world !!
hello world !

Dart remove string last character substring

 

Method 2: Using regex :

replaceAll is a string method defined as below :

String replaceAll(Pattern from, String replace);

It replaces all substring defined by from is replaced by a new string replace and returns that new string.

So, to remove the last character of a string, we can match it using a regular expression and replace it with a blank space. The final program looks as like below :

import 'dart:io';

main() {
  print("Enter a string : ");
  var userInput = stdin.readLineSync();
  print(userInput.replaceAll(RegExp(r'.$'), ""));
}

In regex world, . is used to match any single character except the newline character and $ is used to define the end of a string. So, .$ picks the last character of a string. We are replacing it with an empty string or “”.

 

Sample output :

Enter a string : 
hello
hell

Enter a string : 
hello world
hello worl

Enter a string : 
hello world !!
hello world !

Dart remove string last character regex

Categories: dart

0 Comments

Leave a Reply

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