Creating an Array from a String Separated by Spaces

Creating an array from a string separated by spaces

See explode

// Example 1
$pizza = "piece1 piece2 piece3 piece4 piece5 piece6";
$pieces = explode(" ", $pizza);
echo $pieces[0]; // piece1
echo $pieces[1]; // piece2

Split string by spaces into an array

String#split doesn't actually need an argument if you want to split around whitespaces :

"15 17 21 46".split
#=> ["15", "17", "21", "46"]

If you want to specify an argument, you need to use a space, not an empty string :

"15 17 21 46".split(' ')
#=> ["15", "17", "21", "46"]

And if you want to convert those strings to integers :

"15 17 21 46".split(' ').map(&:to_i)
#=> [15, 17, 21, 46]

GNU Make: How to set an array from a space-separated string?

It's generally a really bad idea to use eval and shell inside a recipe. A recipe is already a shell script so you should just use shell scripting.

It's not really clear exactly what you want to do. If you want to do this in a recipe, you can use a shell loop:

%::
TARGETS=$$(grep -Ph "^[^\t].*::.*##" ./Makefile | cut -d : -f 1 | sort); \
for t in $$TARGETS; do \
echo $$t; \
done

If you want to do it outside of a recipe you can use the GNU make foreach function.

how to convert an integer string separated by space into an array in JAVA

You are forgetting about

  • resetting temp to empty string after you parse it to create place for new digits
  • that at the end of your string will be no space, so

    if (numbers.charAt(i) == ' ') {
    ary[j] = Integer.parseInt(temp);
    j++;
    }

    will not be invoked, which means you need invoke

    ary[j] = Integer.parseInt(temp);

    once again after your loop


But simpler way would be just using split(" ") to create temporary array of tokens and then parse each token to int like

String numbers = "12 1 890 65";
String[] tokens = numbers.split(" ");
int[] ary = new int[tokens.length];

int i = 0;
for (String token : tokens){
ary[i++] = Integer.parseInt(token);
}

which can also be shortened with streams added in Java 8:

String numbers = "12 1 890 65";
int[] array = Stream.of(numbers.split(" "))
.mapToInt(token -> Integer.parseInt(token))
.toArray();

Other approach could be using Scanner and its nextInt() method to return all integers from your input. With assumption that you already know the size of needed array you can simply use

String numbers = "12 1 890 65";
int[] ary = new int[4];

int i = 0;
Scanner sc = new Scanner(numbers);
while(sc.hasNextInt()){
ary[i++] = sc.nextInt();
}

turn string separated by spaces to arraylist of integers in one line

You can use Integer#valueOf. Note you should use Stream#map and not Steam#mapToInt though:

List<Integer> nextLine = 
Arrays.stream(inputLine.split(" "))
.map(Integer::valueOf)
.collect(Collectors.toList());

Reading a space-delimited string into an array in Bash

In order to convert a string into an array, create an array from the string, letting the string get split naturally according to the IFS (Internal Field Separator) variable, which is the space char by default:

arr=($line)

or pass the string to the stdin of the read command using the herestring (<<<) operator:

read -a arr <<< "$line"

For the first example, it is crucial not to use quotes around $line since that is what allows the string to get split into multiple elements.

See also: https://github.com/koalaman/shellcheck/wiki/SC2206

How do I convert a string to an array with spaces preserved in Ruby?

Use String#scan Instead of String#split

You don't want to use String#split because that won't preserve your spaces. You want to use String#scan or String#partition instead. Using Unicode character properties, you can scan for matches with:

'Hello   world!'.scan /[\p{Alnum}\p{Punct}]+|\p{Space}+/
#=> ["Hello", " ", "world!"]

You can also use POSIX character classes (pronounced "bracket expressions" in Ruby) to do the same thing if you prefer. For example:

'Hello   world!'.scan /[[:alnum:][:punct:]]+|[[:space:]]+/
#=> ["Hello", " ", "world!"]

Either of these options will be more robust than solutions that rely on ASCII-only characters or literal whitespace atoms, but if you know your strings won't include other types of characters or encodings then those solutions will work too.

Using Metacharacters for Brevity, Cautiously

If you're looking for brevity in your regular expression, and you're sure you won't need to concern yourself with Unicode characters or explicitly differentiating between non-whitespace characters and punctuation, you can also use the \s and \S metacharacters. For example:

'Hello   world!'.scan /\s+|\S+/
#=> ["Hello", " ", "world!"]

This is generally less robust than the character properties or bracket expressions above, but is still unambiguous, short, and easy to read. It fits your example, so it's worth mentioning, but the \S metacharacter can match control characters and other unexpected things, so you need to be cautious with it unless you really know your data. For example, your string might contain an invisible NUL or a control character like CTRL-D, in which case \S would catch it and return a Unicode-escaped character:

"\x00".scan /\S+/
#=> ["\u0000"]

?\C-D.scan /\S+/
#=> ["\u0004"]

This is probably not what you'd expect, but given a larger data set this type of thing inevitably happens. The more explicit you can be, the fewer problems you're likely to have with your production data.

Using String#partition

For the very simple use case in your original example, you only have two words separated by whitespace. That means you can also use String#partition to partition on the sequential whitespace. That will split the string into exactly three elements, preserving the whitespace that partitions the words. For example:

'Hello   world!'.partition /\s+/
#=> ["Hello", " ", "world!"]

While simpler, the partitioning approach won't work as well with longer strings such as:

'Goodbye   cruel world!'.partition /\s+/
#=> ["Goodbye", " ", "cruel world!"]

so String#scan is going to be a better and more flexible approach for the general use case. However, anytime you want to split a string into three elements, or to preserve the partitioning element itself, #partition can be very handy.

Convert a String containing space separated numbers into an integer array

In a functional way, using Java 8 streams:

int[] y = Arrays.stream(x.split(" ")).mapToInt(Integer::parseInt).toArray();


Related Topics



Leave a reply



Submit