Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter/Dart: Split string by first occurrence

Tags:

split

dart

Is there a way to split a string by some symbol but only at first occurrence?

Example: date: '2019:04:01' should be split into date and '2019:04:01'
It could also look like this date:'2019:04:01' or this date : '2019:04:01' and should still be split into date and '2019:04:01'

string.split(':');

I tried using the split() method. But it doesn't have a limit attribute or something like that.

like image 928
Frederik Avatar asked Feb 25 '20 19:02

Frederik


People also ask

How do you split strings in flutter Dart?

Dart Split String You can split a string with a substring as delimiter using String. split() method. The function returns a list of strings.

How do you split a string on the first occurrence of certain characters?

To split a JavaScript string only on the first occurrence of a character, call the slice() method on the string, passing it the index of the character + 1 as a parameter. The slice method will return the portion of the string after the first occurrence of the character.

How do you split on the first occurrence?

Use the str. split() method with maxsplit set to 1 to split a string on the first occurrence, e.g. my_str. split('-', 1) . The split() method only performs a single split when the maxsplit argument is set to 1 .

How do you split a string into two parts in flutter?

split method Null safety const string = 'Hello world! '; final splitted = string. split(' '); print(splitted); // [Hello, world!]; If the pattern doesn't match this string at all, the result is always a list containing only the original string.


2 Answers

You were never going to be able to do all of that, including trimming whitespace, with the split command. You will have to do it yourself. Here's one way:

String s = "date   :   '2019:04:01'";
int idx = s.indexOf(":");
List parts = [s.substring(0,idx).trim(), s.substring(idx+1).trim()];
like image 146
WaltPurvis Avatar answered Oct 17 '22 20:10

WaltPurvis


You can split the string, skip the first item of the list created and re-join them to a string.

In your case it would be something like:

var str = "date: '2019:04:01'";
var parts = str.split(':');
var prefix = parts[0].trim();                 // prefix: "date"
var date = parts.sublist(1).join(':').trim(); // date: "'2019:04:01'"

The trim methods remove any unneccessary whitespaces around the first colon.

like image 22
nvi9 Avatar answered Oct 17 '22 19:10

nvi9