Created
March 9, 2012 19:47
-
-
Save davidalencar/2008305 to your computer and use it in GitHub Desktop.
Quebra um texto em linhas de tamanho X sem quebrar palavras
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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