Home > Enterprise >  How to split a string in Flutter while also including delimiters
How to split a string in Flutter while also including delimiters

Time:06-27

37.4054-122.0999/ The above coordinates are my output. I want to split the string in such a way that it shows 37.4054 and -122.0999 as substrings which includes the and - signs.

CodePudding user response:

Try use split method:

const string = ' 37.4054-122.0999';
final splitted = string.split('-');
print(splitted); //[' 37.4054', '122.0999'];
print(splitted[0]); // 37.4054;
print('-'   splitted[1]); //-122.0999;

CodePudding user response:

Try this:

void main() {
 final String coord = ' 37.4054-122.0999';
  
  final int plusIndex = coord.indexOf(' ');
  final int minusIndex = coord.indexOf('-');
  
  final plus = coord.substring(plusIndex, minusIndex);
  final minus = coord.substring(minusIndex, );
  
  print('plus: $plus, minus: $minus');
}

CodePudding user response:

You can do

string.split(RegExp('(?=[ -])'));

Example:

  var string = ' 37.4054-122.0999';
  var string2 = '-37.4054 122.0999';
  var string3 = ' 37.4054 122.0999';
  var string4 = '-37.4054-122.0999';
  var a = string.split(RegExp('(?=[ -])'));
  var b = string2.split(RegExp('(?=[ -])'));
  var c = string3.split(RegExp('(?=[ -])'));
  var d = string4.split(RegExp('(?=[ -])'));

  print(a);
  print(b);
  print(c);
  print(d);

Output:

[ 37.4054, -122.0999]
[-37.4054,  122.0999]
[ 37.4054,  122.0999]
[-37.4054, -122.0999]
  • Related