Word wrap a string in multiple lines

2019-01-03 06:49发布

I am trying to word wrap a string into multiple lines. Every line will have defined width.

For example I would get this result if I word wrap it to an area of 120 pixels in width.

Lorem ipsum dolor sit amet,
consectetur adipiscing elit. Sed augue
velit, tempor non vulputate sit amet,
dictum vitae lacus. In vitae ante
justo, ut accumsan sem. Donec
pulvinar, nisi nec sagittis consequat,
sem orci luctus velit, sed elementum
ligula ante nec neque. Pellentesque
habitant morbi tristique senectus et
netus et malesuada fames ac turpis
egestas. Etiam erat est, pellentesque
eget tincidunt ut, egestas in ante.
Nulla vitae vulputate velit. Proin in
congue neque. Cras rutrum sodales
sapien, ut convallis erat auctor vel.
Duis ultricies pharetra dui, sagittis
varius mauris tristique a. Nam ut
neque id risus tempor hendrerit.
Maecenas ut lacus nunc. Nulla
fermentum ornare rhoncus. Nulla
gravida vestibulum odio, vel commodo
magna condimentum quis. Quisque
sollicitudin blandit mi, non varius
libero lobortis eu. Vestibulum eu
turpis massa, id tincidunt orci.
Curabitur pellentesque urna non risus
adipiscing facilisis. Mauris vel
accumsan purus. Proin quis enim nec
sem tempor vestibulum ac vitae augue.

8条回答
2楼-- · 2019-01-03 07:18

Here's a version I came up with for my XNA game...

(Note that it's a snippet, not a proper class definition. Enjoy!)

using System;
using System.Text;
using Microsoft.Xna.Framework.Graphics;

public static float StringWidth(SpriteFont font, string text)
{
    return font.MeasureString(text).X;
}

public static string WrapText(SpriteFont font, string text, float lineWidth)
{
    const string space = " ";
    string[] words = text.Split(new string[] { space }, StringSplitOptions.None);
    float spaceWidth = StringWidth(font, space),
        spaceLeft = lineWidth,
        wordWidth;
    StringBuilder result = new StringBuilder();

    foreach (string word in words)
    {
        wordWidth = StringWidth(font, word);
        if (wordWidth + spaceWidth > spaceLeft)
        {
            result.AppendLine();
            spaceLeft = lineWidth - wordWidth;
        }
        else
        {
            spaceLeft -= (wordWidth + spaceWidth);
        }
        result.Append(word + space);
    }

    return result.ToString();
}
查看更多
相关推荐>>
3楼-- · 2019-01-03 07:19

You can get the (approximate) width of a string from the System.Drawing.Graphics class using the MeasureString() method. If you need a very precise width, I think you have to use the MeasureCharacterRanges() method. Here is some sample code using the MeasureString() method to do roughly what you asked for:

using System;
using System.Collections.Generic; // for List<>
using System.Drawing; // for Graphics and Font

private List<string> GetWordwrapped(string original)
{
    List<string> wordwrapped = new List<string>();

    Graphics graphics = Graphics.FromHwnd(this.Handle);
    Font font = new Font("Arial", 10);

    string currentLine = string.Empty;

    for (int i = 0; i < original.Length; i++)
    {
        char currentChar = original[i];
        currentLine += currentChar;
        if (graphics.MeasureString(currentLine, font).Width > 120)
        {
            // exceeded length, back up to last space
            int moveback = 0;
            while (currentChar != ' ')
            {
                moveback++;
                i--;
                currentChar = original[i];
            }
            string lineToAdd = currentLine.Substring(0, currentLine.Length - moveback);
            wordwrapped.Add(lineToAdd);
            currentLine = string.Empty;
        }
    }

    return wordwrapped;
}
查看更多
The star\"
4楼-- · 2019-01-03 07:23

The following code, taken from this blogpost, will help to get your job done.

You can use it this way:

string wordWrappedText = WordWrap( <yourtext>, 120 );

Please note that the code is not mine, I am just reporting here the main function for your commodity.

protected const string _newline = "\r\n";

public static string WordWrap( string the_string, int width ) {
    int pos, next;
    StringBuilder sb = new StringBuilder();

    // Lucidity check
    if ( width < 1 )
        return the_string;

    // Parse each line of text
    for ( pos = 0; pos < the_string.Length; pos = next ) {
        // Find end of line
        int eol = the_string.IndexOf( _newline, pos );

        if ( eol == -1 )
            next = eol = the_string.Length;
        else
            next = eol + _newline.Length;

        // Copy this line of text, breaking into smaller lines as needed
        if ( eol > pos ) {
            do {
                int len = eol - pos;

                if ( len > width )
                    len = BreakLine( the_string, pos, width );

                sb.Append( the_string, pos, len );
                sb.Append( _newline );

                // Trim whitespace following break
                pos += len;

                while ( pos < eol && Char.IsWhiteSpace( the_string[pos] ) )
                    pos++;

            } while ( eol > pos );
        } else sb.Append( _newline ); // Empty line
    }

    return sb.ToString();
}

/// <summary>
/// Locates position to break the given line so as to avoid
/// breaking words.
/// </summary>
/// <param name="text">String that contains line of text</param>
/// <param name="pos">Index where line of text starts</param>
/// <param name="max">Maximum line length</param>
/// <returns>The modified line length</returns>
public static int BreakLine(string text, int pos, int max)
{
  // Find last whitespace in line
  int i = max - 1;
  while (i >= 0 && !Char.IsWhiteSpace(text[pos + i]))
    i--;
  if (i < 0)
    return max; // No whitespace found; break at maximum length
  // Find start of whitespace
  while (i >= 0 && Char.IsWhiteSpace(text[pos + i]))
    i--;
  // Return length of text before whitespace
  return i + 1;
}
查看更多
萌系小妹纸
5楼-- · 2019-01-03 07:24

Thanks! I take metod from as-cii answer with some changes, for using it in windows forms. Using TextRenderer.MeasureText instead of FormattedText:

static List<string> WrapText(string text, double pixels, Font font)
{
string[] originalLines = text.Split(new string[] { " " }, 
    StringSplitOptions.None);

List<string> wrappedLines = new List<string>();

StringBuilder actualLine = new StringBuilder();
double actualWidth = 0;

foreach (var item in originalLines)
{
    int w = TextRenderer.MeasureText(item + " ", font).Width;
    actualWidth += w;

    if (actualWidth > pixels)
    {
        wrappedLines.Add(actualLine.ToString());
        actualLine.Clear();
        actualWidth = w;
    }

    actualLine.Append(item + " ");
}

if(actualLine.Length > 0)
    wrappedLines.Add(actualLine.ToString());

return wrappedLines;
}

And a little remark: the line actualLine.Append(item + " "); need to be placed after checking width, because if actualWidth > pixels, this word must be in the next line.

查看更多
▲ chillily
6楼-- · 2019-01-03 07:28
static void Main(string[] args)
{
    List<string> lines = WrapText("Add some text", 300, "Calibri", 11);

    foreach (var item in lines)
    {
        Console.WriteLine(item);
    }

    Console.ReadLine();
}

static List<string> WrapText(string text, double pixels, string fontFamily, 
    float emSize)
{
    string[] originalLines = text.Split(new string[] { " " }, 
        StringSplitOptions.None);

    List<string> wrappedLines = new List<string>();

    StringBuilder actualLine = new StringBuilder();
    double actualWidth = 0;

    foreach (var item in originalLines)
    {
        FormattedText formatted = new FormattedText(item, 
            CultureInfo.CurrentCulture, 
            System.Windows.FlowDirection.LeftToRight,
            new Typeface(fontFamily), emSize, Brushes.Black);

        actualLine.Append(item + " ");
        actualWidth += formatted.Width;

        if (actualWidth > pixels)
        {
            wrappedLines.Add(actualLine.ToString());
            actualLine.Clear();
            actualWidth = 0;
        }
    }

    if(actualLine.Length > 0)
        wrappedLines.Add(actualLine.ToString());

    return wrappedLines;
}

Add WindowsBase and PresentationCore libraries.

查看更多
成全新的幸福
7楼-- · 2019-01-03 07:31
public static string GetTextWithNewLines(string value = "", int charactersToWrapAt = 35, int maxLength = 250)
        {
            if (string.IsNullOrWhiteSpace(value)) return "";

            value = value.Replace("  ", " ");
            var words = value.Split(' ');
            var sb = new StringBuilder();
            var currString = new StringBuilder();

            foreach (var word in words)
            {
                if (currString.Length + word.Length + 1 < charactersToWrapAt) // The + 1 accounts for spaces
                {
                    sb.AppendFormat(" {0}", word);
                    currString.AppendFormat(" {0}", word);
                }
                else
                {
                    currString.Clear();
                    sb.AppendFormat("{0}{1}", Environment.NewLine, word);
                    currString.AppendFormat(" {0}", word);
                }
            }

            if (sb.Length > maxLength)
            {
                return sb.ToString().Substring(0, maxLength) + " ...";
            }

            return sb.ToString().TrimStart().TrimEnd();
        }
查看更多
登录 后发表回答