Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!
  • Go

Idiom #356 Parse list of integers

Create the list of integers items for the string s containing integers separated by one or more whitespace characters (space, tab, newline).

import "fmt"
import "strconv"
parts := strings.Fields(s)
items := make([]int, len(parts))
for i, part := range parts {
	v, err := strconv.Atoi(part)
	if err != nil {
		return err
	}
	items[i] = v
}

strings.Fields treats repeated spaces as a single separator.
import java.util.List;
import java.util.Scanner;
Scanner t = new Scanner(s);
List<Integer> items = t.tokens()
    .map(Integer::parseInt)
    .toList();
t.close();

Note, the `toList` method will return an immutable `List`.

New implementation...
< >
programming-idioms.org