获取字符串预览

本文关键字:字符串 获取 | 更新日期: 2023-09-27 18:17:47

我正在寻找的是一种方法来预览字符串。假设字符串有150个字符长。但是我只想显示前50个字符

获取字符串预览

试试s.Substring(0,Math.Min(s.Length,50))

下面是一个使用String的示例。Format和string.Substring()。这个原则几乎适用于任何地方。

using System;
using System.Text;
namespace ConsoleApplication1
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            // let's make a pseudo-random long string
            var longString = new StringBuilder("abcdefghijklmnopqrstuvwxyz0123456789");
            var r = new Random((int) DateTime.Now.Ticks);
            for (int i = 0; longString.Length < 256; i++)
            {
                longString.Insert(r.Next(0, longString.Length - 1)
                                  , (!(Math.IEEERemainder(i, 3) < 0.5)
                                         ? longString[i].ToString().ToUpper()
                                         : longString[i].ToString()));
            }

            // Let's see what our long string looks like...
            Console.WriteLine(longString);
            // Now, let's display the first 50 characters of our long string
            // followed by "..." to indicate that there is more.
            var shortstring = String.Format("{0}...",longString.ToString().Substring(0, 50));
            Console.WriteLine(shortstring);
            //Wait for user to hit a key while results are reviewed.
            Console.ReadKey();
        }
    }
}

string s = "150 characters.....";
s.Substring(0,50);