2

If I'm given a pointer to an array of chars, say

char *c = ....

and c points to an array of chars that looks like

0=A&1=B&2=C&3=D&4=E&5=F&6=G&7=H&8=I&9=J&10=K&11=L

How would I go about getting just the values in this query string, and turning it either into another char array or a std string that looks like this:

ABCDEFGHIJKL

Edit: Also, I suppose you can convert the char array that c points to into a string first too, I'm just unsure how to parse the string.
Edit 2: Also, what might be handy to know is that the value can be only 1 character long (so only 1 letter). However, the names (the numbers) can be however many digits long...

varatis
  • 14,494
  • 23
  • 71
  • 114
  • This problem looks isomorphic to [splitting a string using a delimiter](http://stackoverflow.com/q/909289/1170277). – mavam Apr 26 '12 at 16:43

5 Answers5

1

assuming you have boost the following should work.

std::string str(c);
std::remove_if(str.begin(), str.end(), boost::is_any("123456789&="));

If not we can make our own.

struct is_any {
    std::string filter; 
    is_any(std::string filter) : filter(filter) {}
    bool operator()(char a){ return filter.find(a) != std::string::npos;}
}
andre
  • 7,018
  • 4
  • 43
  • 75
0

Use boost::split(). See this answer to a similar question https://stackoverflow.com/a/236976/10468

Community
  • 1
  • 1
DarenW
  • 16,549
  • 7
  • 63
  • 102
0

If you don't want or can't use Boost, you can also extract the values like this:

const char *query="0=A&1=B&2=C&3=D&4=E&5=F&6=G&7=H&8=I&9=J&10=K&11=L";
std::string values;
for (const char *p=query+1; *p; ++p) 
  if (p[-1]=='=')
    values += *p;

The string values contains the result.

Martin
  • 1,748
  • 1
  • 16
  • 15
0
std::vector<char> results;
const char* str = "0=A&1=B&2=C&3=D&4=E&5=F&6=G&7=H&8=I&9=J&10=K&11=L";
const char* str_end = str + strlen(str);
const char* token = strstr(str, "=");
while(token && (token + 1 < str_end))
{
   results.push_back(*(++token));
   first_token = strstr(token, "=");
}
0

Good old string iteration:

char* str = "0=A&1=B&2=C&3=D&4=E&5=F&6=G&7=H&8=I&9=J&10=K&11=L";
int str_sz = strlen(str);

char dst[str_sz+1];
memset(dst, 0, str_sz+1);
int idx = 0;

for (int i = 0; i < str_sz; i++)
{   
    if (str[i] == '=')
    {   
        dst[idx] = str[i+1];
        idx++;
    }   
}   

std::cout << dst << std::endl;
karlphillip
  • 92,053
  • 36
  • 243
  • 426