How can I convert a comma-separated string to an array?
var array = string.split(',');
MDN reference, mostly helpful for the possibly unexpected behavior of the limit
parameter. (Hint: "a,b,c".split(",", 2)
comes out to ["a", "b"]
, not ["a", "b,c"]
.)
How to split a comma-separated string?
You could do this:
String str = "...";
List<String> elephantList = Arrays.asList(str.split(","));
Basically the .split()
method will split the string according to (in this case) delimiter you are passing and will return an array of strings.
However, you seem to be after a List of Strings rather than an array, so the array must be turned into a list by using the Arrays.asList()
utility. Just as an FYI you could also do something like so:
String str = "...";
ArrayList<String> elephantList = new ArrayList<>(Arrays.asList(str.split(","));
But it is usually better practice to program to an interface rather than to an actual concrete implementation, so I would recommend the 1st option.
Split a comma-delimited string into an array?
Try explode:
$myString = "9,admin@example.com,8";
$myArray = explode(',', $myString);
print_r($myArray);
Output :
Array
(
[0] => 9
[1] => admin@example.com
[2] => 8
)
Converting a comma separated string into an array
Modify the string so that it's valid JSON, then JSON.parse()
it:
var str = '"alpha", "beta", "gamma", "delta"';var json = '[' + str + ']';var array = JSON.parse(json);
console.log(array[0])
how to convert array of object to comma separated array of object
Why not! just turn it to JSON format, then remove open or closed square-brackets:
let arr = [{name:"k"},{name:"p"}];
console.log(JSON.stringify(arr).replace(/\[|\]/g,''))
Result as expected: {"name":"k"},{"name":"p"}
split and flatten array of comma separated strings
In this case you could just join and split again:
const a = ["jan,feb,may", "apr,may,sept,oct", "nov,jan,mar", "dec", "oct,feb,jan"];
const res = a.join().split(',');
console.log(res);
How to convert array into comma separated string in javascript
The method array.toString()
actually calls array.join()
which result in a string concatenated by commas. ref
var array = ['a','b','c','d','e','f'];document.write(array.toString()); // "a,b,c,d,e,f"
How to arrange comma separated string in Arrays of String in c?
You have several issues to work through to convert your function from simply printing the separated strings to stdout
to saving the separated strings in ArrayOfString
. Before getting to the changes, let's avoid using magic numbers in your code.
char ArrayOfString[10][5];
In ArrayOfString
above, 10
and 5
are magic numbers. They are hardcoded values that will govern everything from the declaration size to required validation checks to protect your array bounds. Instead of hardcoding values, if you need a constant, define one (or more), e.g.
#include <stdio.h>
#include <string.h>
#define ROW 10
#define COL 5
char ArrayOfString[ROW][COL];
Now on to separating your string into tokens. The C-library provides a function specifically tailored to separating delimited strings into tokens. Conveniently named strtok
. The only caveat to know about strtok
is that it modifies the string, so if you need to preserve the original, make a copy first.
To use strtok (string, delims)
to separate string
into tokens at delims
, your first call to strtok
takes string
as the 1st parameter. All subsequent calls use NULL
in its place. You can either make an initial call to strtok
and then use a while loop to complete the process, or a for
loop is tailor made for handling the initial call, as well as all subsequent calls with NULL
.
For example your function utilizing strtok
to separate string
into tokens and providing a size_t
return of the number of tokens copied to ArrayOfString
could be similar to:
char ArrayOfString[ROW][COL];
size_t vSeparateSringByComma (char* string)
{
const char *delims = ",\n";
char *s = string;
size_t n = 0, len;
for (s = strtok (s, delims); s && n < ROW; s = strtok (NULL, delims))
if ((len = strlen (s)) < COL)
strcpy (ArrayOfString[n++], s);
else
fprintf (stderr, "error: '%s' exceeds COL - 1 chars.\n", s);
return n;
}
(note: how your array bounds are protected both by the check with n < ROW
and each row array bound is protected with (len = strlen (s)) < COL
before the copy to ArrayOfString[n++]
is made)
(also note: how by not using magic numbers, if you change the ROW
or COL
size in the future, only the constants need changing and the change is automatically incorporated throughout your code by virtue of using constants)
Your example program would then be:
int main(void) {
char string[] = "$,0,3,307,183,18,5,119,1,#";
size_t n = vSeparateSringByComma (string);
for (size_t i = 0; i < n; i++)
printf ("ArrayOfString[%zu] : '%s'\n", i, ArrayOfString[i]);
}
Example Use/Output
$ ./bin/arrayofstrings
ArrayOfString[0] : '$'
ArrayOfString[1] : '0'
ArrayOfString[2] : '3'
ArrayOfString[3] : '307'
ArrayOfString[4] : '183'
ArrayOfString[5] : '18'
ArrayOfString[6] : '5'
ArrayOfString[7] : '119'
ArrayOfString[8] : '1'
ArrayOfString[9] : '#'
Using strcspn
and strspn
Instead of strtok
As discussed in the comments, using strcspn
to report the number of sequential characters not containing a delimiter allowing you to determined the length of each field. You then need to skip over the delimiters (which in many cases can be made up of more than one delimiter (e.g. $, 0, 3, ...
).
While strtok
considers multiple sequential delimiters a single delimiter, you would need a similar way to skip over the intervening delimiters to position your self to read the next field. strspn
will work nicely using the same delims
, but this time reporting the number of characters made up of only characters within delims
(allowing you to add that to your len
and then len
to s
to position yourself for the next read)
A short variation using strcspn
and strspn
could be:
size_t vSeperateSringByComma (char* string)
{
const char *delims = ",\n";
char *s = string;
size_t n = 0, len;
while ((len = strcspn (s, delims))) { /* number of non-delim chars */
if (len < COL) { /* validate it will fit */
memcpy (ArrayOfString[n], s, len); /* copy len chars */
ArrayOfString[n++][len] = 0; /* nul terminate at len */
}
else
fprintf (stderr, "error: '%s' exceeds COL - 1 chars.\n", s);
len += strspn (s + len, delims); /* scan past delimiter(s) */
s += len; /* update s to beginning of next field */
}
return n;
}
(the output is the same)
Look things over and let me know if you have further questions.
How to convert a comma separated string field to array in mongodb
Considering the amount of data, I would definitely run this directly on the server. Here is an example that works to use as a guide. It will replace the names
field with a new array from the $split
.
db.collectionName.aggregate(
[
{ "$addFields": {
"names": { "$split": [ "$names", "," ] }
}},
{$out:"collectionName"}
]
)
Related Topics
PHP Crop Image to Fix Width and Height Without Losing Dimension Ratio
Executing a Powershell Script from PHP
PHP SQL Join Together Multiple Tables from Different Databases
Forget Password Page, Creating a Generated Password to Email to the User
Filling Gaps in Dates Returned from Database - Pure SQL Solution Possible
PHP Readfile VS. File_Get_Contents
How to Define Global Functions in PHP
Downloading a File with a Different Name to the Stored Name
MySQL Can't Perform More Than 1 Query at a Time
How to Query Employee Details and Relate Their Performance Metrics
Access Joomla 2.5 from External Script to Get Article by Id
How to Convert Iso8601 to Date Format in PHP
How to Explain the Result for a New \Datetime('0000-00-00 00:00:00')