How to return the first 100 characters of type string if the string is initially empty or less than 100 characters? Applied the Substring function, but got exception on a string less than 100 characters long.

.Substring (0, 100) + "...";

  • 3
    for example Math.Min(100, string.Length) - Grundy

5 answers 5

 string str = "123456ldfsgks"; int maxLength = 100; string result = str.Substring(0, Math.Min(str.Length, maxLength)); Console.WriteLine(result); 
  • is to paint what the code does in response - Grundy
 string result = new string(str.Take(100).ToArray()); 

    You can build about this extension method

      public static string SafeSubstring(this string text, int startIndex, int length) { //защищаСмся ΠΎΡ‚ null строки if (text == null) return string.Empty; //ΡƒΠ·Π½Π°Π΅ΠΌ Π΄Π»ΠΈΠ½Ρƒ "хвоста" ΠΎΡ‚ Π½Π°Ρ‡Π°Π»ΡŒΠ½ΠΎΠΉ ΠΏΠΎΠ·ΠΈΡ†ΠΈΠΈ для Π²Ρ‹Π±ΠΎΡ€ΠΊΠΈ тСкста var tailLength = text.Length - startIndex; //Ссли "хвоста" Π½Π΅Ρ‚, Π·Π½Π°Ρ‡ΠΈΡ‚ стартовая позиция Π·Π° ΠΏΡ€Π΅Π΄Π΅Π»Π°ΠΌΠΈ ΠΎΡ€ΠΈΠ³ΠΈΠ½Π°Π»ΡŒΠ½ΠΎΠΉ строки //Π½Π΅Ρ‡Π΅Π³ΠΎ Π²Ρ‹Π±ΠΈΡ€Π°Ρ‚ΡŒ if (tailLength <= 0) return string.Empty; //Π²Ρ‹Π±ΠΈΡ€Π°Π΅ΠΌ наимСньшСС Π·Π½Π°Ρ‡Π΅Π½ΠΈΠ΅. МоТно ΠΏΡ€ΠΈΠΌΠ΅Π½ΠΈΡ‚ΡŒ Math.Min if (tailLength < length) length = tailLength; //Ρ‚Π΅ΠΏΠ΅Ρ€ΡŒ с ΠΏΡ€Π°Π²ΠΈΠ»ΡŒΠ½Ρ‹ΠΌΠΈ числами Π²Ρ‹Π±ΠΈΡ€Π°Π΅ΠΌ подстроку return text.Substring(startIndex, length); } 

      It is also possible to add an increment through foreach () and read if the character 100 counted, then just exit the break; And if it is less than 100, then it will output everything. And without errors.

       public string Text(string text) { int i = 1; string itog = ""; foreach (char a in text) { if (i <= 100) { itog += a; i++; } else { break; } } return itog; } 

        It is possible and so:

         public static string GetFirstCharactersOfString(string inputString, int maxLength) { return (String.IsNullOrEmpty(inputString) || inputString.Length <= maxLength) ? inputString : inputString.Remove(maxLength); } 

        Check the length of the string, if it is less than or equal to the number of characters that we want to get maxLength , or the string is empty or null , then we will return the input string. If the string is larger, we cut the string and return the first maxLength characters with the String.Remove Method .


        Or like this:

         public static string GetFirstCharactersOfString(string inputString, int maxLength) { return (!String.IsNullOrEmpty(inputString) && inputString.Length >= maxLength) ? inputString.Substring(0, maxLength) : inputString; } 

        Also, check the length of the string, if it is less than or equal to the number of characters that we want to get maxLength , or the string is empty or null , then we will return the input string, otherwise, we will cut the string using the String.Substring method


        Using String.IsNullOrEmpty - method - check if the specified string is null or Empty.