Skip to content

Instantly share code, notes, and snippets.

@davidalencar
Created March 9, 2012 19:47
Show Gist options
  • Save davidalencar/2008305 to your computer and use it in GitHub Desktop.
Save davidalencar/2008305 to your computer and use it in GitHub Desktop.
Quebra um texto em linhas de tamanho X sem quebrar palavras
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace QuebrarLinhas
{
public class QuebradorDeLinhas
{
private string texto;
private int tamanhoDaLinha;
public QuebradorDeLinhas(string texto, int tamanhoDaLinha)
{
this.texto = texto;
this.tamanhoDaLinha = tamanhoDaLinha;
}
public string TextoFormatado()
{
StringBuilder stb = new StringBuilder();
List<string> linhas = this.LinhasDoTexto();
foreach (var item in linhas)
{
stb.AppendLine(item);
}
return stb.ToString();
}
private List<string> LinhasDoTexto()
{
var linhas = new List<string>();
int inicio = 0, fim = tamanhoDaLinha;
while (fim == tamanhoDaLinha)
{
if (inicio + fim > texto.Length)
fim = texto.Length - inicio;
var t1 = texto.Substring(inicio, fim);
if (fim == tamanhoDaLinha)
t1 = t1.Substring(0, t1.LastIndexOf(" "));
linhas.Add(t1.Trim());
inicio += t1.Length;
}
return linhas;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment