如何将字符串转换为缩写形式?

Nic*_*kis 6 c++ string algorithm mfc abbreviation

我想适应串到特定的宽度.例如,"Hello world" - >"...... world","Hello ...","He ...... rld".

你知道我在哪里可以找到代码吗?这是一个巧妙的技巧,对于表示信息非常有用,我想在我的应用程序中添加它(当然).

编辑:对不起,我忘了提到字体部分.不只是固定宽度的字符串,而是根据字体的面貌.

Sma*_*ery 8

如果你无法在任何地方找到它,这是一个非常简单的编写自己的算法 - 伪代码将是这样的:

if theString.Length > desiredWidth:
    theString = theString.Left(desiredWidth-3) + "...";
Run Code Online (Sandbox Code Playgroud)

或者如果你想在字符串开头的省略号,那第二行将是:

    theString = "..." + theString.Right(desiredWidth-3);
Run Code Online (Sandbox Code Playgroud)

或者如果你想要它在中间:

    theString = theString.Left((desiredWidth-3)/2) + "..." + theString.Right((desiredWidth-3)/2 + ((desiredWidth-3) mod 2))
Run Code Online (Sandbox Code Playgroud)

编辑:
我假设你正在使用MFC.由于您需要使用字体,因此可以使用CDC :: GetOutputTextExtent函数.尝试:

CString fullString
CSize size = pDC->GetOutputTextExtent(fullString);
bool isTooWide = size.cx > desiredWidth;
Run Code Online (Sandbox Code Playgroud)

如果那个太大了,那么你可以进行搜索,试着找到你能装的最长的字符串; 它可以像你想要的那样聪明 - 例如,你可以尝试"Hello Worl ..."然后"Hello Wor ..."然后"Hello Wo ..."; 删除一个字符,直到找到它为止.或者,您可以进行二进制搜索 - 尝试"Hello Worl ..." - 如果这不起作用,那么只使用原始文本的一半字符:"Hello ..." - 如果适合,请尝试中间它和:"Hello Wo ...",直到找到最长的仍然适合.或者您可以尝试一些估计启发式(将总长度除以所需长度,按比例估计所需的字符数,然后从那里搜索.

简单的解决方案是这样的:

unsigned int numberOfCharsToUse = fullString.GetLength();
bool isTooWide = true;
CString ellipsis = "...";
while (isTooWide)
{
    numberOfCharsToUse--;
    CString string = fullString.Left(numberOfCharsToUse) + ellipsis;
    CSize size = pDC->GetOutputTextExtent(string);
    isTooWide = size.cx > desiredWidth;
}
Run Code Online (Sandbox Code Playgroud)