c# - 将 vector<unsigned char> {1,2,3} 转换为字符串 "1-2-3"AS DIGITS

标签 c# c++ string vector data-conversion

我想在 std::vector<unsigned char> 中显示数字在屏幕上,但在发送给收件人的途中,我需要将这些数字填充到 std::string 中.

无论我尝试什么( atoireinterpret_caststring.c_str() ...),要么是胡说八道,要么是这些原始数字的字母表示 - 即它们对应的 ascii 字符。

那么我如何轻松(最好是标准方法)转换 vector<unsigned char> {1,2,3}进入 string "1-2-3"

在我提到的原始帖子(后来编辑)中,我可以用 C# 或 Java 来做到这一点。 应 πìντα ῥεῖ 的要求提供 C# 或 Java 示例,这里是一个快速的 Linq C# 方式:

    public static string GetStringFromListNumData<T>(List<T> lNumData)
    {
        // if (typeof(T) != typeof(IConvertible)) throw new ArgumentException("Expecting only types that implement IConvertible !");
        string myString = "";
        lNumData.ForEach(x => myString += x + "-");
        return myString.TrimEnd('-');
    }

最佳答案

我是这样处理的:

std::vector<unsigned char> v {1, 2, 3};

std::string s; // result

auto sep = ""; // continuation separator
for(auto n: v)
{
    s += sep + std::to_string(n);
    sep = "-"; // change the continuation separator after first element
}

std::cout << s << '\n';

continuation separator 开始时为空,并在连接第一个输出后发生变化。

输出:

1-2-3

关于c# - 将 vector<unsigned char> {1,2,3} 转换为字符串 "1-2-3"AS DIGITS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36137997/

相关文章:

c++ - Box2D:导致 "Polygon is degenerate"的三角形

c++ - 为什么 C++ 标准要求编译器忽略对基本类型的转换运算符的调用?

c# - 如何在 ASP.NET 服务器端使用剪贴板

c# - Windows Phone 中动画编译错误

c# - 使用 Polly C# 库处理异常的正确方法

c++ - CMake Exported Lib - 在客户端应用程序中找不到包含/lib 路径

c++ - 当许多 unordered_map<string, double> 具有完全相同的字符串设置为键时如何节省内存

c# - 如何将字符串解析为 BigInteger?

c++ - printf 字符串输出 "Dz↕"getch() C++

c# - 比较两个 List<string> 是否相等