在 C++ 中,将 int[] 转换为 String 可以通过以下方法实现:
#include<iostream>
#include <sstream>
#include<string>
int main() {
int arr[] = {1, 2, 3, 4, 5};
int size = sizeof(arr) / sizeof(arr[0]);
std::ostringstream oss;
for (int i = 0; i< size; ++i) {
oss<< arr[i];
if (i< size - 1) {
oss << ", ";
}
}
std::string result = oss.str();
std::cout << "String: "<< result<< std::endl;
return 0;
}
#include<iostream>
#include<string>
#include<vector>
int main() {
int arr[] = {1, 2, 3, 4, 5};
int size = sizeof(arr) / sizeof(arr[0]);
std::vector<std::string> str_arr;
for (int i = 0; i< size; ++i) {
str_arr.push_back(std::to_string(arr[i]));
}
std::string result = "";
for (int i = 0; i< size; ++i) {
result += str_arr[i];
if (i< size - 1) {
result += ", ";
}
}
std::cout << "String: "<< result<< std::endl;
return 0;
}
这两种方法都可以将 int[] 转换为 String,具体使用哪种方法取决于您的需求和编程风格。
领取专属 10元无门槛券
手把手带您无忧上云