Split long string in multi lines in C#

140 Views Asked by At

I'm fetching data from Dynamics CRM and some fields are of type Multiple Line of Text.

I can only read them as a string using en.GetAttributeValue<string>("multiline_field_name").

My problem is that I'm rendering said string in an HTML markup and some words break.

e.g

container div
************************
This is a very long stri
ng. Any help would be ve
ry much appreciated.
************************

My container element can contain just a bit over 100 characters so I thought I'd break the string on every 100th character.

This is my code:

    private string SplitOnNewLine(string str)
    {
    
       StringBuilder sb = new StringBuilder();
    
       int splitOnIndex = 100;
       int cnt = 1;
    
       for(int i = 0; i <str.Length; i++)
       {
          if(i % splitOnIndex == 0 && i != 0)
          {
              if(str[i] == ' ')
              {
                  sb.Insert(i, "<br>");
              }
              else
              {
                  // Go backwards until space is found and append line break
    
                  int copied = splitOnIndex * cnt;
                  if (copied >= str.Length) break;
    
                   do
                   {
                      copied--;
                      if(str[copied] == ' ')
                      {
                         sb.Insert(copied, "<br>");
                         break;
                      }
                   }while (str[copied] != ' ');
               }
               cnt++;
            }
            else
            {
                sb.Append(str[i]);
            }
       }          
       return sb.ToString();
}

It still doesn't work as expected. I'd expect something like this:

container div
************************
This is a very long 
string. Any help would 
be very much 
appreciated.
************************

P.S. I've also tried using word-break and word-wrap CSS rules to no avail.

1

There are 1 best solutions below

2
MiniMik On BEST ANSWER

How is about split in two strings after every 100 chars, do a reverse find of e.g. ' ' and do this recursive with the second part of the string as you did already.

string output = "";
        
for(int i = 0; i < input.Length; )
{
     string part = input.Substring( i, ( input.Length - i < 100 )? input.Length - i : 100 );

     if ( part.Length < 100 )
     {
         output += "<br>";
         output += input.Substring( i ).TrimStart();
         break;
     }
     else
     { 
         int lastSpaceInLine =  part.LastIndexOf( ' ' );

         if ( i != 0 )
              output += "<br>";

         output += input.Substring( i, lastSpaceInLine ).TrimStart();
         i += lastSpaceInLine;
      }
 }

Ok, now I had the chance to check the code... now it does as expected...