2
* Copyright (C) 2004 Laurent Mazet
4
* This program is free software; you can redistribute it and/or modify
5
* it under the terms of the GNU General Public License as published by
6
* the Free Software Foundation; either version 2 of the License, or
7
* (at your option) any later version.
9
* This program is distributed in the hope that it will be useful,
10
* but WITHOUT ANY WARRANTY; without even the implied warranty of
11
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12
* GNU General Public License for more details.
14
* You should have received a copy of the GNU General Public License
15
* along with this program; If not, see <http://www.gnu.org/licenses/>.
22
#include <octave/oct.h>
23
#include <octave/Cell.h>
25
DEFUN_DLD (csvexplode, args, nargout,
27
"@deftypefn {Function File} {@var{c} = } csvexplode (@var{str})\n"
28
"@deftypefnx {Function File} {@var{c} = } csvexplode (@var{str}, @var{sep})\n"
29
"@deftypefnx {Function File} {@var{c} = } csvexplode (@var{str}, @var{sep}, @var{prot})\n"
31
"Explode a CSV string into a cell. "
32
"@var{sep} changes the character used to separate two fields. By "
33
"default, two fields are expected to be separated by a coma "
34
"(@code{,}). @var{prot} changes the character used to protect a string. "
35
"By default it's a double quote (@code{\"}).\n"
39
if ((args.length() < 1) || (args.length() > 3)) {
41
return octave_value();
45
if (!args(0).is_string()) {
46
if (args(0).is_cell())
47
return octave_value(args(0));
49
return octave_value(Cell(args(0)));
51
std::string str = args(0).string_value();
53
std::string _sep = (args.length() > 1) ? args(1).string_value() : ",";
54
if (_sep.length() != 1) {
55
error("Only on charactere need as separator\n");
56
return octave_value();
60
std::string _prot = (args.length() > 2) ? args(2).string_value() : "\"";
61
if (_prot.length() != 1) {
62
error("Only on charactere need as protector\n");
63
return octave_value();
67
/* Explode a line into a cell */
71
for (int i=0, len=str.length(); i<=len; i++) {
72
if (((i==len) || (str[i] == sep)) && (!inside)) {
75
retval.resize(dim_vector(1, retval.columns()+1));
78
const char *word_str=word.c_str();
80
double val = strtod (word_str, &err);
82
/* Store into the cell */
83
retval(0, retval.columns()-1) =
84
((word == "") || (err != word_str+word.length())) ?
85
octave_value(word) : octave_value(val);
89
else if ((inside) && (str[i]==prot) && ((i<len) && (str[i+1]==prot))) {
91
/* Insisde a string */
95
else if (str[i] == prot)
102
return octave_value(retval);