[英]Convert a string from Java to C++
我在Java中有這個字符串:
String op="text1 "+z+" text2"+j+" text3"+i+" "+Arrays.toString(vol);
其中“z”,“j”和“i”是int變量; “toString()”是屬於一個類的函數。
class Nod
{
private:
char *op;
public:
char Nod::toString()
{
return *op;
}
}
和“vol”是int變量的向量。
我想把它轉換成C ++。
你能幫我嗎?
編輯:
抱歉,因為我混淆了你,但“toString()” 不是屬於某個類的函數。
“Arrays.toString()” - 是一個來自Java的類。
要將int
附加到字符串中,可以使用std::stringstream
:
#include <sstream>
#include <string>
std::stringstream oss;
oss << "text1 " << z << " text2" << j << " text3" << i;
std::string str = oss.str();
方法str()
返回一個string
其中包含流內容的副本。
編輯:
如果你有一個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];
或者有一種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);
你可以看看std::to_string
。
以下是此代碼的實例。
請記住,並非所有編譯器都支持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.