Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a string from Java to C++

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.

like image 988
Romulus Avatar asked Aug 18 '13 21:08

Romulus


People also ask

How do you convert a string to a char in 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.

How do I convert a string to an int?

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.

How do I convert a string to an int in Java?

The method generally used to convert String to Integer in Java is parseInt() of String class.


1 Answers

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.

like image 77
Pierre Fourgeaud Avatar answered Sep 30 '22 00:09

Pierre Fourgeaud