How to take input in an Array in Dart?

Issue

I need to ask the user to input any quantity of space/comma-separated integers and add them to an array to then bubble sort them. I only need help with taking an input in an array. I’m losing brain cells, please.

Examples of an input:
10, 9, 8, 6, 7, 2, 3, 4, 5, 1

or:
10 9 8 6 7 2 3 4 5 1

I found some reference code in python, don’t know if it’s useful:

//——————————–str_arr = raw_input().split(‘ ‘)

//——————————–arr = [int(num) for num in str_arr]

Solution

You can split by using a RegExp:

import 'dart:io';

void main() {
  const input1 = '10, 9, 8, 6, 7, 2, 3, 4, 5, 1';
  const input2 = '10 9 8 6 7 2 3 4 5 1';
  const input3 = '10,9,8,6,7,2,3,4,5,1';

  final regexp = RegExp(r'(?: |, |,)');

  print(input1.split(regexp)); // [10, 9, 8, 6, 7, 2, 3, 4, 5, 1]
  print(input2.split(regexp)); // [10, 9, 8, 6, 7, 2, 3, 4, 5, 1]
  print(input3.split(regexp)); // [10, 9, 8, 6, 7, 2, 3, 4, 5, 1]

  print('Please enter line of numbers to sort:');
  final input = stdin.readLineSync();

  final listOfNumbers = input.split(regexp).map(int.parse).toList();

  print('Here is your list of numbers:');
  print(listOfNumbers);
}

Answered By – julemand101

Answer Checked By – Cary Denson (FlutterFixes Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *