简体   繁体   English

如何计算格式化字符串的长度

[英]How to work out length of a formatted string

I'm wanting to display a message on the console window, as long as the message won't exceed the default 0-79 X width of the window.The code I have looks like: 我想在控制台窗口上显示一条消息,只要该消息不会超过窗口的默认0-79 X宽度。我的代码如下所示:

int xRemaining = 80 - mRobot.CurrentPos.X;
string message = "ID{0:d} Facing {1:s} at ({2:d},{3:d}) home is({4:d},{5:d})";
string formatMessage = string.Format(message,mRobot.ID,mRobot.getDir.ToString()/*...*/;

if(mRobot.CurrentPos.Y < 24)
{
  if (xRemaining < formatMessage.Length)
    {
     Console.SetCursorPosition((mRobot.CurrentPos.X - xRemaining), mRobot.CurrentPos.Y+1); 
    }
  else
    {
     Console.SetCursorPosition(mRobot.CurrentPos.X, mRobot.CurrentPos.Y + 1);
    }
}

else
{
  if(xRemaining < formatMessage.Length)
  {
   Console.SetCursorPosition((mRobot.CurrentPos.X-xRemaining), mRobot.CurrentPos.Y-1);
  }
  else
   {
    Console.SetCursorPosition(mRobot.CurrentPos.X, mRobot.CurrentPos.Y-1);
   }
}
Console.Write(message,,mRobot.ID, mRobot.getDir.ToString(), mRobot.CurrentPos.X, mRobot.CurrentPos.Y,mRobot.Home.X,mRobot.Home.Y);

Edit: Used string.Format, still seems to be running onto the next line though :/ 编辑:使用过的string.Format,虽然:/似乎仍在运行到下一行

You can format message with string.Format method: 您可以使用string.Format方法格式化消息:

string message = "ID{0:d} Facing {1:s} at ({2:d,3:d}) home is({4:d,5:d})";
string formattedMessage = string.Format(message, mRobot.ID, mRobot.getDir.ToString(), /* ... */);
int msgLength = formattedMessage.Length;

Later on, you can just display it with: 稍后,您可以使用以下命令显示它:

Console.WriteLine(formattedMessage);

You need to format the string before getting it's length. 您需要先格式化字符串,然后再获取其长度。 You are currently getting the length of the unformatted string. 当前,您正在获取未格式化字符串的长度。 To do that you need to use the string.Format command: 为此,您需要使用string.Format命令:

string output = string.Format(message, .....);

....

if (xRemaining < output.Length)
{
    ....
}

....

Console.Write(output);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM