Is There an Equivalent in C++ of PHP's Explode() Function

Is there an equivalent in C++ of PHP's explode() function?

Here's a simple example implementation:

#include <string>
#include <vector>
#include <sstream>
#include <utility>

std::vector<std::string> explode(std::string const & s, char delim)
{
std::vector<std::string> result;
std::istringstream iss(s);

for (std::string token; std::getline(iss, token, delim); )
{
result.push_back(std::move(token));
}

return result;
}

Usage:

auto v = explode("hello world foo bar", ' ');

Note: @Jerry's idea of writing to an output iterator is more idiomatic for C++. In fact, you can provide both; an output-iterator template and a wrapper that produces a vector, for maximum flexibility.

Note 2: If you want to skip empty tokens, add if (!token.empty()).

C alternative to PHP's explode function

Use strtok(). From the man page for it:

The strtok() function parses a string into a sequence of tokens. On
the first call to strtok() the string to be parsed should be specified
in str. In each subsequent call that should parse the same string, str
should be NULL.

Each call to strtok() returns a pointer to a null-terminated string
containing the next token. This string does not include the delimiting
byte. If no more tokens are found, strtok() returns NULL.

In other words, loop through your string and keep calling strtok() until it returns NULL in order to get all the words (that would be split on the delimiters specified to the first call of strtok()) returned as char*.

Parallel to PHP's explode in C: Split char* into char* using delimiter

You can use strtok like CrazyCasta said but his/hers code is wrong.

char *tok;
char *src = malloc(strlen(srcStr) + 1);
memcpy(src, srcStr);

tok = strtok(src, "#");
if(tok == NULL)
{
printf("no tokens found");
free(src);
return ???;
}
printf("%s ; ", tok);
while((tok = strtok(NULL, "#")))
printf("%s ; ", tok);
printf("\n");
free(str);

Be aware that strtok has to be called the first time with the source pointer, after that you have to use NULL. Also src must be writeable because strtok writes \0 to terminate the found strings. Hence, depending on how you read the string (and whether you are going to use it afterwards or not), you should do a copy of it. But as I said, this is not always necessary.

EDIT:

an explode function could look like this:

char *strdup(const char *src)
{
char *tmp = malloc(strlen(src) + 1);
if(tmp)
strcpy(tmp, src);
return tmp;
}

void explode(const char *src, const char *tokens, char ***list, size_t *len)
{
if(src == NULL || list == NULL || len == NULL)
return;

char *str, *copy, **_list = NULL, **tmp;
*list = NULL;
*len = 0;

copy = strdup(src);
if(copy == NULL)
return;

str = strtok(copy, tokens);
if(str == NULL)
goto free_and_exit;

_list = realloc(NULL, sizeof *_list);
if(_list == NULL)
goto free_and_exit;

_list[*len] = strdup(str);
if(_list[*len] == NULL)
goto free_and_exit;
(*len)++;

while((str = strtok(NULL, tokens)))
{
tmp = realloc(_list, (sizeof *_list) * (*len + 1));
if(tmp == NULL)
goto free_and_exit;

_list = tmp;

_list[*len] = strdup(str);
if(_list[*len] == NULL)
goto free_and_exit;
(*len)++;
}

free_and_exit:
*list = _list;
free(copy);
}

then you have to call it:

char **list;
size_t i, len;
explode("this;is;a;string", ";", &list, &len);
for(i = 0; i < len; ++i)
printf("%d: %s\n", i+1, list[i]);

/* free list */
for(i = 0; i < len; ++i)
free(list[i]);
free(list);

this is an example running with valgrind:

valgrind ./a 
==18675== Memcheck, a memory error detector
==18675== Copyright (C) 2002-2010, and GNU GPL'd, by Julian Seward et al.
==18675== Using Valgrind-3.6.0.SVN-Debian and LibVEX; rerun with -h for copyright info
==18675== Command: ./a
==18675==
1: this
2: is
3: a
4: string
==18675==
==18675== HEAP SUMMARY:
==18675== in use at exit: 0 bytes in 0 blocks
==18675== total heap usage: 9 allocs, 9 frees, 114 bytes allocated
==18675==
==18675== All heap blocks were freed -- no leaks are possible
==18675==
==18675== For counts of detected and suppressed errors, rerun with: -v
==18675== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 4 from 4)

Alternative of php's explode/implode-functions in c#

String.Split() will explode, and String.Join() will implode.

Is there any powerbuilder function which is equivalent to PHP's explode function

Not built-in but the PFC String Service has of_parse_to_array() which does the same thing as PHP's explode(), except for limit. If you're not using PFC you could just lift of_parse_to_array() (keeping the copyright notice, of course), or you could grab pfc_n_base, n_base, pfc_n_cst_string, and n_cst_string and have the whole string service. If you really need limit, it's easy to add an overloaded version of of_parse_to_array() that implements limit.

Objective C version of explode()?

NSArray *stringArray = [myString componentsSeparatedByString:@":"];

Javascript Equivalent to PHP Explode()

This is a direct conversion from your PHP code:

//Loading the variable
var mystr = '0000000020C90037:TEMP:data';

//Splitting it with : as the separator
var myarr = mystr.split(":");

//Then read the values from the array where 0 is the first
//Since we skipped the first element in the array, we start at 1
var myvar = myarr[1] + ":" + myarr[2];

// Show the resulting value
console.log(myvar);
// 'TEMP:data'

What is for Python what 'explode' is for PHP?

Choose one you need:

>>> s = "Rajasekar SP  def"
>>> s.split(' ')
['Rajasekar', 'SP', '', 'def']
>>> s.split()
['Rajasekar', 'SP', 'def']
>>> s.partition(' ')
('Rajasekar', ' ', 'SP def')

str.split and str.partition

Visual C++ is there something like explode for Strings?

There's no direct equivalent, but the Tokenize method is similar, and can be used as the basis of function to work like PHP's explode.

Equivalent of explode(), str_replace() in ASP

IMPORTANT:

It is now clear that this question is .Net not asp-classic but for anyone who ends up here looking for Classic ASP equivalents of these functions carry on reading.


Classic ASP Equivalent Functions

There are equivalents for both these functions in Classic ASP


explode() is used to split a string into an array using another string.
The equivalent in Classic ASP is called (funnily enough) Split() and can be used like so;

Dim list, template
'This will give you a list array variable containing the array elements from the Split().
list = Split(template, "INSERT CONTENT HERE")

str_replace() is used to replace occurrences of a search string inside another.
The equivalent in Classic ASP is called (bet you can't guess) Replace() and can be use like so;

Dim template
template = Replace(template, "src=""content""", "src=""http://staging.domain.edu/content/""")


Related Topics



Leave a reply



Submit