Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
777 views
in Technique[技术] by (71.8m points)

c# - Convert vector<unsigned char> {1,2,3} into string "1-2-3" AS DIGITS

I want to display numbers in a std::vector<unsigned char> on a screen, but on its way to the recipient, I need to stuff these numbers into a std::string.

Whatever I tried (atoi, reinterpret_cast, string.c_str() ...), gave me either a nonsense, or a letter representation of those original numbers - i.e. their corresponding ascii characters.

So how do I easily (preferably standard method) convert vector<unsigned char> {1,2,3} into a string "1-2-3"?

In the Original Post (later edited) I mentioned, that I could do that in C# or Java. Upon the request of π?ντα ?ε? to provide example in C# or Java, here is a quick Linq C# way:

    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('-');
    }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Here is how I handle that:

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 << '
';

The continuation separator starts out empty and gets changed after concatenating the first output.

Output:

1-2-3

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...