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
188 views
in Technique[技术] by (71.8m points)

c++ - How to break up a CString that does not have any delimiters within it?

I have a CString that I want to break up into small strings. It is a string consisting of a constant 2 byte header and 2 byte footer, but the rest of the string has no discernible pattern. I need to break them up based on sizes: so the first two bytes become the header, then I need to extract the next 2, then 3 and so on. (these numbers are in no pattern either)

Example:

CString test = "1010eefabbccde1f1f"

I need

CString header = "1010";
CString test1  = "eefa";
CString test2  = "bbccde";
CString footer = "1f1f";

I read about sscanf being used for this purpose, but I have only managed to use it split strings into int.

Example:

CString test = '101022223333331010';
int a,b,c,d;
sscanf(test,"%02d%02d%03d%02d",&a,&b,&c,&d); 

This works for strings containing only numbers. But when I do the same for strings by changing %d to %s, exceptions get raised.

Is there a better way to do this?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

My understanding is that given an input string test and vector<size_t> sizes of sizes, you wish to break the string apart into those sizes, and then you wish to take those parts, treat them as hex numbers, and return them in vector<int> result.

I'm going to presume that you have already tested test to ensure the correct number of characters exist. And I'm going to assume that the sizes include the header and footer sizes.

After running something like this:

const auto test = "1010eefabbccde1f1f"s;
const vector<size_t> sizes { 4U, 4U, 6U, 4U };
const auto result = accumulate(cbegin(sizes), cend(sizes), vector<int>(), [&, pos = 0U](auto& a, const auto& b) mutable {
    a.push_back(stoi(test.substr(pos, b), nullptr, 16));
    pos += b;
    return a;
});

result will contain:

4112
61178
12307678
7967

Live Example


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

...