How to remove string character using index in Dart

Introduction :

Sometimes we need to remove one character from a string using its index. The string is immutable. We can’t modify it. The only way is to create one different new string from the old one.

In this post, I will show you how to remove one character from a string using its index in dart.

How to solve it :

To solve this problem, we will create two substrings from the original string. One from index 0 to just before the character that we are removing and another from the character just after the character that we are removing. We will join these two substrings to get the final required string.

For example, if our string is Helllo and if we want to remove the character at index 2, we will join two substrings: the first one from index 0 to 1 and the second one from index 3 to the end.

substring method :

Generating a substring from a string is easy. Dart provides one method called substring that returns one substring from a string. This method is defined as below :

substring(startIndex, [endIndex])

Here, startIndex is the starting index of the string that we will get the substring from. endIndex is optional. If we don’t provide it, it will take the substring to the end of the given string.

Below is the final program :

void main() {
  String givenStr = 'Helllo';
  int i = 4;

  String finalStr = givenStr.substring(0, i) + givenStr.substring(i + 1);
  print(finalStr);
}

It will print the below output :

Hello

Similar tutorials :