Home > OS >  Remove first 3 letters from String in list Dart
Remove first 3 letters from String in list Dart

Time:10-31

I want to remove the first 3 letters from every item (String) in my List.

My Listitems look like this:

{2: test1.mp4
3: test2.mp4
4: test3.mp4
10: test4.mp4
11: test5.mp4

I want to remove the "{2: " from the firs item and for every other item i want to remove the number the space, so that i only have the file name.

CodePudding user response:

the substring method is the solution for your case :

String text = "11: test5.mp4";
String result = text.substring(3); //  test5.mp4

and if you just want to remove extra space on sides, use trim method

 String text = "     test5.mp4    ";
 String result = text.trim(); // test5.mp4

CodePudding user response:

It will probably be better to use split() instead of trimming off the white space and using a set index.

const track = '11: test5.mp4';
final splitted = track.split(': ');
print(splitted); // [11, test5.mp4];

CodePudding user response:

Currently it's a little bit unclear how your list looks exactly. I am assuming, you have the following list:

List<String> myList = [
  "2: test1.mp4",
  "3: test2.mp4",
  "4: test3.mp4",
  "10: test4.mp4",
  "11: test5.mp4",
];

In this case, it's not necessarily only the first 3 letters that you want to remove. A scalable solution would be the following:

final List<String> myList = [
  "2: test1.mp4",
  "3: test2.mp4",
  "4: test3.mp4",
  "10: test4.mp4",
  "11: test5.mp4",
];


//We are splitting each item at ": ", which gives us a new array with two 
//items (the number and the track name) and then we grab the last item of
//that array.
final List<String> myFormatedList = myList.map((e) => e.split(": ").last).toList();

print(myFormatedList);
//[test1.mp4, test2.mp4, test3.mp4, test4.mp4, test5.mp4]
  • Related