开发者

Concatenating different patterns of string

开发者 https://www.devze.com 2023-01-11 04:57 出处:网络
I\'m writing a function which concatenates different numbers of strings depending on their length. Here is some c++ like pseudo code of what I\'m currently doing:

I'm writing a function which concatenates different numbers of strings depending on their length.

Here is some c++ like pseudo code of what I'm currently doing:

string foo(size_t maxLength)
{
    string a, b, c, d, e, ret;

    //...assign them

    if(a.size() + b.size() + c.size() + d.size() + e.size() <= maxLength)
    {
        ret = a + b + c + d + e;
    }
    else if(a.size() + c.size() + d.size() + e.size() <= maxLength)
    {
        LOG << "B was removed.";
        ret = a + c + d + e;
    }
    else if(a.size() + b.size() + c.size() + d.size() <= maxLength)
    {
        LOG << "E was removed"l
        ret = a + b + c + d;
    }
    //... a larg开发者_如何学编程e amount of code like the above

    return ret;    
}

Is there a nice way to clean this up?

Thanks.


To begin with, I'd convert it to array of strings. Then loop through your options and see which permutation actually fits your maxLength.

As quantumSoup commented - you did not mention your criteria for elimination, but once you have this defined, it is easy to iterate the options by eliminating the specific array indices, according to your priority criterion.


If you were just looking to clean it up visually, something like:

    string a, b, c, d, e, ret, temp;

    //...assign them

    temp = a + b + c + d + e;
    if(temp.length <= maxLength) {
        LOG << "none removed";
        ret = temp;
    }

    temp = a + b + c + d;
    if(temp.length <= maxLength) {
        LOG << "e removed";
        ret = temp;
    }    

    temp = a + b + c + e;
    if(temp.length <= maxLength) {
        LOG << "d removed";
        ret = temp;
    }

    //... etc

    return ret;

As ysap mentioned, you can optimise it with loops if you have elimination criteria.


If the order for omitting strings is arbitrary, I'd try to construct a list of some kind ordered by the priority. Then I'd work my way through the list until I'd filled up the output buffer. If as you say the priorities are externally defined and arbitrary, you could probably drive it with constant table.

0

精彩评论

暂无评论...
验证码 换一张
取 消