Search code examples
c#console-applicationword-wrap

c# word wrap, how to limit new line creation based on different words in a string


I've been looking into writing a word wrap console application in C#. I've found a lot of useful examples on here but I'm having issues with what I've currently got.

The code I've currently got will create a new line after every word that "overflows" the columnLimit. I want/need a way of adding a new line only if that word isn't the final one in the string and if possible to add a hyphen when the word overflows between two lines (so it will be a word splitter not a word wrapper).

I know it's probably a really simple solution but I'm new to C# and I'm really stuck on this problem. A coding solution so I can see where I've gone wrong would be ideal.

Can anyone help me with this?

public string formatText(string longSentence, int columnLimit)
{
    string[] words = longSentence.Split(' ');
    StringBuilder newLongSentence = new StringBuilder();
    string line = "";

    foreach (string word in words)
    {
        if ((line + word).Length > columnLimit)
        {
            newLongSentence.AppendLine(line);
            line = "";
        }

        line += string.Format("{0} ", word);
    }

    if (line.Length > 0) 
        newLongSentence.AppendLine(line);

    return newLongSentence.ToString();     
}

Solution

  • You should use the length the the line goes over the limit to do a substring, making your foreach loop look more like this

    foreach (string word in words)
    {
        int extraLetters = columnLimit - (line + word).Length;
        if (extraLetters < 0 && extraLetters != word.Length)
        {
    
            newLongSentence.AppendLine(line + word.Substring(0, word.length + extraLetters));
            line = string.Format("{0} ", word.Substring(word.length + extraLetters + 1));
    
        }
        else if(extraLetters == word.Length)
        {
            newLongSentence.AppendLine(line);
            line = String.Format("{0} ", word);
        }
        else
        {
            line += string.Format("{0} ", word);
        }
    
    }
    

    If you wish to include a dash, take 1 away from the relevant substrings and add a dash like so

    foreach (string word in words)
    {
        int extraLetters = columnLimit - (line + word).Length;
        if (extraLetters < 0 && extraLetters != word.Length && extraLetters != word.Length - 1)
        {
    
            newLongSentence.AppendLine(line + word.Substring(0, word.length + extraLetters - 1) + "-");
            line = string.Format("{0} ", word.Substring(word.length + extraLetters));
    
        }
        else if(extraLetters == word.Length || extraLetters == word.Length - 1)
        {
            newLongSentence.AppendLine(line);
            line = String.Format("{0} ", word);
        }
        else
        {
            line += string.Format("{0} ", word);
        }
    
    }