skip to Main Content

I have a single string made up of numbers of varying lengths, example: "12345"

I would like to break the String before the last character, so that I have ["1234", "5"]

I can do this with substring, but I would like a more simplified way, like using split(), but I don’t know how

Below, example using substring:

 String numbers = '123456';
 var partOne = numbers.substring(0, numbers.length -1);
 var partTwo = numbers.substring(numbers.length -1, numbers.length);
 print('partOne $partOne - partTwo $partTwo'); // partOne 12345 - part Two 6

2

Answers


  1. Is this simpler for you?

    String numbers = '123456';
    List<String> parts = [numbers.substring(0, numbers.length - 1), numbers[numbers.length - 1]];
    print('partOne ${parts[0]} - partTwo ${parts[1]}'); // partOne 12345 - partTwo 6
    
    Login or Signup to reply.
  2. void main(List<String> arguments) {
      const numbers = '123456';
      final re = RegExp('(.*)(.)');
      final match = re.firstMatch(numbers);
      if (match != null) {
        print(match.group(1));
        print(match.group(2));
      }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search