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) + "...";
string str = "123456ldfsgks"; int maxLength = 100; string result = str.Substring(0, Math.Min(str.Length, maxLength)); Console.WriteLine(result); 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.
Source: https://ru.stackoverflow.com/questions/568638/
All Articles
Math.Min(100, string.Length)- Grundy