在字符串C++中将文本居中对齐

r1zk6ea1  于 2024-01-09  发布在  其他
关注(0)|答案(4)|浏览(227)

我一直在尝试用C为一个gameserver DLL做一个函数,它在将新字符串返回给Lua进行处理之前将给定的文本对齐到中心。我花了很多时间在各种网站上查看示例,但只能找到'cout',它在控制台应用程序中打印它,我不希望它这样做。
我是C
的新手,我真的很困惑如何处理这个问题。如果有人能提供一个例子并解释它是如何工作的,我将能够学习如何在未来做到这一点。
基本上,它是这样做的:
1.将我们的字符串从Lua转发到C++。

  1. C++将我们刚刚转发的字符串居中。
    1.将完成的字符串返回给Lua。
    这是我一直在尝试做的一个例子:
  1. int CScriptBind_GameRules::CentreTextForConsole(IFunctionHandler *pH, const char *input)
  2. {
  3. if (input)
  4. {
  5. int l=strlen(input);
  6. int pos=(int)((113-l)/2);
  7. for(int i=0;i<pos;i++)
  8. std::cout<<" ";
  9. std::cout<<input;
  10. return pH->EndFunction(input);
  11. }
  12. else
  13. {
  14. CryLog("[System] Error in CScriptBind_GameRules::CentreTextForConsole: Failed to align");
  15. return pH->EndFunction();
  16. }
  17. return pH->EndFunction();
  18. }

字符串
但它会将文本打印到控制台,而不是转发回完整的字符串。

cyvaqqii

cyvaqqii1#

我假设你已经知道如何将一个字符串从Lua传递到C++,并将结果从C++返回到Lua,所以我们唯一需要处理的部分是生成居中的字符串。
然而,这很容易:

  1. std::string center(std::string input, int width = 113) {
  2. return std::string((width - input.length()) / 2, ' ') + input;
  3. }

字符串

uurity8g

uurity8g2#

这里有另一种方法,将确保文本在给定的宽度内居中,并在左右填充空格。

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

字符串
这可以写得更优雅或简洁。

n9vozmp4

n9vozmp43#

  1. std::string center (const std::string& s, unsigned width)
  2. {
  3. assert (width > 0);
  4. if (int padding = width - s.size (), pad = padding >> 1; pad > 0)
  5. return std::string (padding, ' ').insert (pad, s);
  6. return s;
  7. }

字符串

gmol1639

gmol16394#

下面是一个使用std::format(C++20)的更现代的解决方案。

  1. std::string center(const std::string &s, size_t width)
  2. {
  3. return std::format("{:^{}}", s, width);
  4. }

字符串

相关问题