[英]Convert a string from Java to C++
I have this string in Java: 我在Java中有这个字符串:
String op="text1 "+z+" text2"+j+" text3"+i+" "+Arrays.toString(vol);
where "z", "j" and "i" are int variables; 其中“z”,“j”和“i”是int变量; "toString()" is a function belongs to a class.
“toString()”是属于一个类的函数。
class Nod
{
private:
char *op;
public:
char Nod::toString()
{
return *op;
}
}
and "vol" is a vector of int variables. 和“vol”是int变量的向量。
and I want to convert it into C++. 我想把它转换成C ++。
Can you help me please? 你能帮我吗?
EDIT: 编辑:
Sorry because I confuse you, but "toString()" is not a function belongs to a class. 抱歉,因为我混淆了你,但“toString()” 不是属于某个类的函数。
"Arrays.toString()" - is a class from Java. “Arrays.toString()” - 是一个来自Java的类。
To append an int
into string, you can use the std::stringstream
: 要将
int
附加到字符串中,可以使用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. 方法
str()
返回一个string
其中包含流内容的副本。
EDIT : 编辑:
If you have a std::vector
, you can do : 如果你有一个
std::vector
,你可以这样做:
#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 : 或者有一种C ++ 11方法可以做所有事情:
#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
. 你可以看看
std::to_string
。
Here is a live example of this code. 以下是此代码的实例。
Remember that not all the compilers support C++11 as of right now. 请记住,并非所有编译器都支持C ++ 11。
std::to_string
是在C ++ 11中执行此操作的另一种方法(不需要为sstream
额外的include
):
std::string op = "text1 " + std::to_string(num);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.