Align text to center in string C++

前端 未结 3 1424
既然无缘
既然无缘 2021-01-17 07:45

I have been trying to make a function in C++ for a gameserver DLL which aligns given text to center before returning the new string to Lua for processing. I have spent quite

相关标签:
3条回答
  • 2021-01-17 08:24

    Here's another way that will ensure the text is centered within a given width and is padded left and right with spaces.

    std::string center(const std::string s, const int w) {
        std::stringstream ss, spaces;
        int pad = w - s.size();                  // count excess room to pad
        for(int i=0; i<pad/2; ++i)
            spaces << " ";
        ss << spaces.str() << s << spaces.str(); // format with padding
        if(pad>0 && pad%2!=0)                    // if pad odd #, add 1 more space
            ss << " ";
        return ss.str();
    }
    

    This could be written more elgantly or concisely.

    0 讨论(0)
  • 2021-01-17 08:30
    std::string center (const std::string& s, unsigned width)
    {
        assert (width > 0);
        if (int padding = width - s.size (), pad = padding >> 1; pad > 0)
            return std::string (padding, ' ').insert (pad, s);
        return s;
    }
    
    0 讨论(0)
  • 2021-01-17 08:46

    I'm going to assume you already know how to pass a string from Lua to C++ and return the result from C++ to Lua, so the only part we need to deal with is producing the centered string.

    That, however, is pretty easy:

    std::string center(std::string input, int width = 113) { 
        return std::string((width - input.length()) / 2, ' ') + input;
    }
    
    0 讨论(0)
提交回复
热议问题