C++: How to copy a string object to an int array?

431 Views Asked by At

I have a string of numbers in C++: like string str="1234567012"

  1. I wish to copy this to an int array, such that each element of the array will have one digit. Now I can use an iterator, and iterate one at a time and use static_cast<int>(*iter). But is there any more easier and straightforward method?

  2. finally i want to recopy the int array to a string array.

Please help me with above 2 steps.

2

There are 2 best solutions below

5
R. Martinho Fernandes On BEST ANSWER

You can use the std::transform function:

std::vector<int> ints(str.size());
std::transform(str.begin(), str.end(), ints.begin(),
               [](char c) { return c - '0'; });

If your compiler doesn't support lambdas yet, you can use a regular function:

int get_digit(char c) { return c - '0'; }

// ...
std::transform(str.begin(), str.end(), ints.begin(), get_digit);

To do the reverse operation, you can do similarly:

std::string s(ints.size(), 0);
std::transform(ints.begin(), ints.end(), s.begin(),
               [](int i) { return i + '0'; });
5
Kerrek SB On

Something like this:

std::vector<int> v;
v.reserve(str.size());
for (char c : str) { v.push_back(c - '0'); }

//...

string s;
for (int i : v)  { s += i + '0'; }