Search code examples
c#stringfunctionnewlinechars

cut a string from right side to maximal 25 chars even when string is less than 25 chars, remove newlines of all kinds


In C# windows forms application I have strings of different length and format from which I would like to display a preview of the first 25 characters without containing any line breaks of any kind in the preview. The preview string should be followed by " ...".

I have some strings less than 25 chars but they also can contain line breaks or sometimes not. the newline can be like <br>, <br />, /n, /r, /r/n, /n/n or an Environment.Newline like in C#. With shorter strings I get exceptions because of the TextX.SubString(0, 25) cannot be applied.

What ready function in the framework would do it the best way? Maybe you have any idea how to solve this.

At the end should be appended the " ...", but since the string is already defined there can't be attached something to it TextX.Append doesn't exist in the content.


Solution

  • It seems, that there's no ready function in a framework, but you can do something like this:

      public static String Preview(String value) {
        String[] newLines = new String[] { "<br>", "<br />", "\n", "\r", Environment.NewLine };
    
        foreach (String newLine in newLines)
          value = value.Replace(newLine, ""); // <- May be space will be better here
    
        if (text.Length > 25) 
          return value.Substring(0, 25) + "…"; 
          // If you want string END, not string START, comment out the line above and uncomment this
          // return value.Substring(value.Length - 25) + "…";
        else
          return value;
      }
    
      ...
      // Test sample
    
      String text = "abcd<br>efgh\r\r\n\n1234567890zxy\n\n1234567890abc";
      String result = Preview(text); // <- abcdefgh1234567890zxy1234…
    
      String text2 = "abcd<br>efgh\r\r";   
      String result2 = Preview(text2); // <- abcdefgh