Skip to content

Instantly share code, notes, and snippets.

@lshaf
Created June 16, 2020 14:25
Show Gist options
  • Save lshaf/b7d095efb63cfda0d374bb1a6ce45b17 to your computer and use it in GitHub Desktop.
Save lshaf/b7d095efb63cfda0d374bb1a6ce45b17 to your computer and use it in GitHub Desktop.
Word wrap in C Sharp
using System;
using System.Collections;
using System.Linq;
public class Program
{
class StringHelper
{
public static ArrayList WordWrap(string text, int maxLength = 86)
{
ArrayList final = new ArrayList();
string tmpText = text.Trim();
string[] spaces = { " ", "\n", "\r\n" };
while (tmpText != "")
{
if (tmpText.Length <= maxLength)
{
final.Add(tmpText.Trim());
tmpText = "";
}
else
{
int tmpLimit = maxLength;
string tmpFinal = tmpText.Substring(0, maxLength);
string lastChar = tmpFinal.Substring(tmpFinal.Length - 1);
if (spaces.Contains(lastChar) == false)
{
int idxLastSpace = 0;
foreach (string space in spaces)
{
int tmpLastSpace = tmpFinal.LastIndexOf(space);
if (tmpLastSpace > idxLastSpace)
{
idxLastSpace = tmpLastSpace;
}
}
Console.WriteLine(idxLastSpace);
tmpLimit = idxLastSpace;
tmpFinal = tmpFinal.Substring(0, tmpLimit);
}
tmpText = tmpText.Substring(tmpLimit, tmpText.Length - tmpLimit).Trim();
final.Add(tmpFinal);
}
}
return final;
}
}
public static void Main()
{
string words = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.";
ArrayList data = StringHelper.WordWrap(words, 30);
foreach (string word in data)
{
Console.WriteLine(word);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment