Word Wrap a String in Multiple Lines

Word wrap a string in multiple lines

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.

Wrap multiline string (preserving existing linebreaks) in Python?

Just add the newlines back after splitting:

import textwrap
import pprint
import itertools

mystr=r"""
First line.
Second line.
The third line is a very long line, which I would like to somehow wrap; wrap at 80 characters - or less, or more! ... can it really be done ??"""

wrapper = textwrap.TextWrapper(width = 80)
mylist = [wrapper.wrap(i) for i in mystr.split('\n') if i != '']
mylist = list(itertools.chain.from_iterable(mylist))

pprint.pprint(mylist)

Output:

['First line.',
'Second line.',
'The third line is a very long line, which I would like to somehow wrap; wrap at',
'80 characters - or less, or more! ... can it really be done ??']

Breaking string into multiple lines according to character width (python)

Since you know the width of each character, you should make that into a dictionary, from which you get the widths to calculate the stringwidth:

char_widths = {
'a': 9,
'b': 11,
'c': 13,
# ...and so on
}

From here you can lookup each letter and use that sum to check your width:

current_width = sum([char_widths[letter] for letter in word])

TextBox : Wrapping text to multiple lines

What is your content? Is it a "human readable" string (e.g. 'normal' words and sentences), or is it a hexadecimal string etc.?

Depending on your content, you have multiple options:

  1. Insert a \n after a certain amount of characters
  2. Depending on your framework (WPF, WinForms etc.) use different properties / implementations.....


    If you are using WPF, try AcceptReturn="true" TextWrapping="Wrap"


    If you are using WinForms, try inserting some \n-characters , when .Multiline := true and .WordWrap := true

ADDENDUM: If you want to insert a \n after every x characters, I have the following snippet for you (which I quite like):

using System.Text.RegularExpressions;

...

string mystr = "this is my very long text";

mystr = Regex.Replace(mystr, "(.{20})", "$1\n");

TextBox1.Text = mystr; // or: TextBox1.Content = mystr;

Where the 20 inside the Regex "(.{20})" your ammount of characters is, after which a \n will be inserted. (meaning, that your string will have a new line after every 20 characters)

Multi-line string in the style of a table with columns and word wrap

I had a moment so I threw a quick answer together. It should be enough to get you going.

//Define how big you want that column to be (i.e the breakpoint for the string)
private const int THRESHOLD = 15;

//Formatter for your "row"
private const string FORMAT = "{0} {1} {2}\n";

public static string GetRowFormat(string name, decimal price1, decimal price2)
{
StringBuilder sb = new StringBuilder();
if(name.Length > THRESHOLD) //If your name is larger than the threshold
{
//Determine how many passes or chunks this string is broken into
int chunks = (int)Math.Ceiling((double)name.Length / THRESHOLD);

//Pad out the string with spaces so our substrings dont bomb out
name = name.PadRight(THRESHOLD * chunks);

//go through each chunk
for(int i = 0; i < chunks; i++)
{
if(i == 0) //First iteration gets the prices too
{
sb.AppendFormat(FORMAT, name.Substring(i * THRESHOLD, THRESHOLD), price1.ToString("C").PadRight(8), price2.ToString("C").PadRight(8));
}
else //subsequent iterations get continuations of the name
{
sb.AppendLine(name.Substring(i * THRESHOLD, THRESHOLD));
}
}
}
else //If its not larger than the threshold then just add the string
{
sb.AppendFormat(FORMAT, name.PadRight(THRESHOLD), price1.ToString("C").PadRight(8), price2.ToString("C").PadRight(8));
}
return sb.ToString();
}

I created a fiddle here

Multiple Line Label with word wrapping

I find it a lot easier to use constraints to set layout rather than manually adjusting the frame...

But if, for whatever reason, you want to manually set the frame of the label I'd suggest two things:

  1. Like like @rmaddy mentions, viewDidLoad is too early in the view controller lifecycle for the frame to be correct. Try overriding layoutSubviews and moving the frame adjustments into that method.

  2. For a UILabel with numberOfLines set to 0, you'll also want to set the labels preferredmaxlayoutwidth property to help it figure out how many lines it needs to be (not needed if using constraints).

Also, if you're willing to target iOS9 and above, UIStackView is really nice addition to UIKit to help with this sort of layout where subviews get pushed down from potential increasing height of multi-line labels.

Here's some screen grabs of adding a stack view to hold 2 UILabels, and then constraints that pin the stackview's left, top, and right edges to the superview:

Sample Image

With the layout defined in your storyboard, your viewDidLoad becomes a lot simpler with just setting the actual content for the labels:

override func viewDidLoad() {
super.viewDidLoad()

self.orgTitle.text = self.oTitle
self.orgDesc.text = self.desc
self.orgImage.image = self.image
}

How do I make a Text widget wrap long text into multiple lines?

This might not be the best solution but this is the only thing working for me.

Surround the Text widget with a Container and set the maximum width of it based on Screen size.

Screen size - 84 seems to be the minimum value to avoid overflow. I've tested it on 2 devices and is working fine.

steps: widget.questions
.map(
(String q) => Step(
title: new Container(
constraints: new BoxConstraints(
maxWidth: MediaQuery.of(context).size.width - 84),
child: Text(q),
),
content: new Container(),
),
)
.toList(),

A good way to make long strings wrap to newline?

You could use textwrap module:

>>> import textwrap
>>> strs = "In my project, I have a bunch of strings that are read in from a file. Most of them, when printed in the command console, exceed 80 characters in length and wrap around, looking ugly."
>>> print(textwrap.fill(strs, 20))
In my project, I
have a bunch of
strings that are
read in from a file.
Most of them, when
printed in the
command console,
exceed 80 characters
in length and wrap
around, looking
ugly.

help on textwrap.fill:

>>> textwrap.fill?

Definition: textwrap.fill(text, width=70, **kwargs)
Docstring:
Fill a single paragraph of text, returning a new string.

Reformat the single paragraph in 'text' to fit in lines of no more
than 'width' columns, and return a new string containing the entire
wrapped paragraph. As with wrap(), tabs are expanded and other
whitespace characters converted to space. See TextWrapper class for
available keyword args to customize wrapping behaviour.

Use regex if you don't want to merge a line into another line:

import re

strs = """In my project, I have a bunch of strings that are.
Read in from a file.
Most of them, when printed in the command console, exceed 80.
Characters in length and wrap around, looking ugly."""

print('\n'.join(line.strip() for line in re.findall(r'.{1,40}(?:\s+|$)', strs)))

# Reading a single line at once:
for x in strs.splitlines():
print '\n'.join(line.strip() for line in re.findall(r'.{1,40}(?:\s+|$)', x))

output:

In my project, I have a bunch of strings
that are.
Read in from a file.
Most of them, when printed in the
command console, exceed 80.
Characters in length and wrap around,
looking ugly.


Related Topics



Leave a reply



Submit