Logo

Programming-Idioms

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

Be concise.

Be useful.

All contributions dictatorially edited by webmasters to match personal tastes.

Please do not paste any copyright violating material.

Please try to avoid dependencies to third-party libraries and frameworks.

Other implementations
#include <string>
#include <vector>
using namespace std;
vector<int> items;
int x, y, n (s.length()), i;
for (x = 0; x not_eq n; ++x)
    if (not isspace(s[x])) {
        for (y = x + 1; y not_eq n; ++y)
            if (isspace(s[y])) break;
        i = stoi(s.substr(x, y - x));
        items.push_back(i);
        x = y - 1;
    }
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
}
import static java.util.Collections.list;
import java.util.StringTokenizer;
var items
    = list(new StringTokenizer(s))
        .stream()
        .map(String::valueOf)
        .mapToInt(Integer::parseInt)
        .toArray();
import java.util.ArrayList;
import java.util.List;
import static java.lang.Character.isWhitespace;
import static java.lang.Integer.parseInt;
List<Integer> items = new ArrayList<>();
int x, y, n = s.length(), i;
for (x = 0; x != n; ++x)
    if (!isWhitespace(s.charAt(x))) {
        for (y = x + 1; y != n; ++y)
            if (isWhitespace(s.charAt(y)))
                break;
        i = parseInt(s.substring(x, y));
        items.add(i);
        x = y - 1;
    }
import java.util.ArrayList;
import static java.util.Arrays.stream;
import static java.util.stream.Collectors.toCollection;
List<Integer> items
    = stream(s.split("\\s+"))
        .map(Integer::valueOf)
        .collect(toCollection(ArrayList::new));
import java.util.Scanner;
var items
    = new Scanner(s)
        .useDelimiter("\\s+")
        .tokens()
        .map(Integer::valueOf)
        .toList();
var
  tmp: array of string;
  items: array of integer;
...  
tmp := s.split(whitespace, TStringsplitOptions.ExcludeEmpty);
SetLength(items, Length(tmp));
for i := Low(tmp) to High(tmp) do items[i] := StrToInt(tmp[i]);
items = [int(x) for x in s.split()]
items = [*map(int, s.split())]
from string import whitespace as ws
items, x, n = [], 0, len(s)
while x != n:
    if s[x] not in ws:
        for y in range(x + 1, n + 1):
            if y == n or s[y] in ws:
                break
        items.append(int(s[x:y]))
        x = y - 1
    x += 1
items = s.split.map(&:to_i)
let items = s
    .split_whitespace()
    .map(|x| x.parse::<i32>().unwrap())
    .collect::<Vec<i32>>();
let items = s
    .split_whitespace()
    .map(|x| x.parse::<i32>().unwrap())
    .collect::<Vec<i32>>();