I have this string in Java:
String op="text1 "+z+" text2"+j+" text3"+i+" "+Arrays.toString(vol);
where "z", "j" and "i" are int variables; "toString()" is a function belongs to a class.
class Nod
{
private:
char *op;
public:
char Nod::toString()
{
return *op;
}
}
and "vol" is a vector of int variables.
and I want to convert it into C++.
Can you help me please?
EDIT:
Sorry because I confuse you, but "toString()" is not a function belongs to a class.
"Arrays.toString()" - is a class from Java.
We can convert String to char in java using charAt() method of String class. The charAt() method returns a single character only. To get all characters, you can use loop.
Use Integer.parseInt() to Convert a String to an Integer This method returns the string as a primitive type int. If the string does not contain a valid integer then it will throw a NumberFormatException.
The method generally used to convert String to Integer in Java is parseInt() of String class.
To append an int
into string, you can use the std::stringstream
:
#include <sstream>
#include <string>
std::stringstream oss;
oss << "text1 " << z << " text2" << j << " text3" << i;
std::string str = oss.str();
The method str()
returns a string
with a copy of the content of the stream.
EDIT :
If you have a std::vector
, you can do :
#include <vector>
std::vector<int> arr(3);
unsigned int size = arr.size();
for ( unsigned int i = 0; i < size; i++ )
oss << arr[i];
Or there is a C++11 way to do all the thing :
#include <string>
#include <vector>
std::vector<int> arr(3);
std::string result = "text1 " + std::to_string(z);
result += " text2" + std::to_string(j);
result += " text3" + std::to_string(i) + " ";
for ( auto& el : arr )
result += std::to_string(el);
You can take a look at std::to_string
.
Here is a live example of this code.
Remember that not all the compilers support C++11 as of right now.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With