How can I truncate my strings with a “…” if they are too long?

前端 未结 11 664
陌清茗
陌清茗 2020-12-13 23:13

Hope somebody has a good idea. I have strings like this:

abcdefg
abcde
abc

What I need is for them to be trucated to show like this if more

11条回答
  •  春和景丽
    2020-12-13 23:34

    I has this problem recently. I was storing a "status" message in a nvarcharMAX DB field which is 4000 characters. However my status messages were building up and hitting the exception.

    But it wasn't a simple case of truncation as an arbitrary truncation would orphan part of a status message, so I really needed to "truncate" at a consistent part of the string.

    I solved the problem by converting the string to a string array, removing the first element and then restoring to a string. Here is the code ("CurrentStatus" is the string holding the data)...

            if (CurrentStatus.Length >= 3750)
            {
                // perform some truncation to free up some space.
    
                // Lets get the status messages into an array for processing...
                // We use the period as the delimiter, then skip the first item and re-insert into an array.
    
                string[] statusArray = CurrentStatus.Split(new string[] { "." }, StringSplitOptions.None)
                                        .Skip(1).ToArray();
    
                // Next we return the data to a string and replace any escaped returns with proper one.
                CurrentStatus = (string.Join(".", statusArray))
                                        .Replace("\\r\\n", Environment.NewLine);
    
    
            }
    

    Hope it helps someone out.

提交回复
热议问题