Dart program to remove the last character of string

How to remove the last string character in Dart:

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: By using the substring method:

The substring method of Dart String class is defined as:

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

It takes two parameters for the start and the end indices of the result string.

  • The first parameter, startIndex is the starting index of the substring(inclusive).
  • The second parameter, endIndex is the end index of the substring(exclusive).

It returns the substring as defined by the start and end indices.

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

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

The following example shows how to use the substring method with user-given strings:

import 'dart:io';

main() {
  print("Enter a string : ");
  var userInput = stdin.readLineSync();

  if (userInput != null) {
    print(userInput.substring(0, userInput.length - 1));
  }
}

Download it on GitHub

Sample output:

If you run the above program, it will print output as below:

Enter a string:
hello
hell

Enter a string:
hello world
hello worl

Enter a string:
hello world !!
hello world !

Dart program to remove the last character of a string

Method 2: By using regex:

We can also use a regular expression to remove the last string character in Dart. The replaceAll is a string method that can be used with a pattern or regex. It is defined as:

String replaceAll(Pattern from, String replace);

It takes one Pattern as its first parameter and a String as the second parameter. It replaces all substrings matched by the pattern from and replaces these with the string replace.

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 below:

import 'dart:io';

main() {
  print("Enter a string: ");
  var userInput = stdin.readLineSync();

  if (userInput != null) {
    print(userInput.replaceAll(RegExp(r'.$'), ""));
  }
}

Download it on GitHub

The character . is used to match any single character except the newline character, and .$ is used to define the end of a string. So, the pattern .$ picks the last character of a string. We are replacing it with an empty string or "".

Sample output:

If you run the above program, it will print outputs as below:

Enter a string :
hello
hell

Enter a string :
hello world
hello worl

Enter a string :
hello world !!
hello world !

Dart program to remove the last character of a string with regex

You might also like: