{"id":2835,"date":"2019-11-11T15:52:38","date_gmt":"2019-11-11T14:52:38","guid":{"rendered":"https:\/\/solidt.eu\/site\/?p=2835"},"modified":"2025-11-07T16:52:57","modified_gmt":"2025-11-07T15:52:57","slug":"c-string-helpers","status":"publish","type":"post","link":"https:\/\/solidt.eu\/site\/c-string-helpers\/","title":{"rendered":"C# StringHelpers \/ String helpers"},"content":{"rendered":"\n<div style=\"height: 250px; position:relative; margin-bottom: 50px;\" class=\"wp-block-simple-code-block-ace\"><pre class=\"wp-block-simple-code-block-ace\" style=\"position:absolute;top:0;right:0;bottom:0;left:0\" data-mode=\"csharp\" data-theme=\"monokai\" data-fontsize=\"14\" data-lines=\"Infinity\" data-showlines=\"true\" data-copy=\"false\">using System;\nusing System.Collections.Generic;\nusing System.Text.RegularExpressions;\n\nnamespace Default\n{\n    public class StringHelpers\n    {\n        \/\/ generics\n        public static IEnumerable&lt;IEnumerable&lt;T>> Split&lt;T>(IEnumerable&lt;T> src, int size) \n                    => src.Where((x, i) => i % size == 0).Select((x, i) => src.Skip(i * size).Take(size));\n\n        public static IEnumerable&lt;T> Select&lt;T>(params T[] args) => args;\n        public static List&lt;T> List&lt;T>(params T[] args) => args.ToList();\n\n\n        \/\/ string specific\n        public static string Join(string separator, params string[] args) => string.Join(separator, args.Where(x => !string.IsNullOrWhiteSpace(x)).Select(x => x.Trim()));\n        public static string BuildLines(params string[] lines) => Join(Environment.NewLine, lines);\n        \n        public static bool StrEquals(string a, string b) => string.Equals((a ?? \"\").Trim(), (b ?? \"\").Trim(), StringComparison.OrdinalIgnoreCase);\n\n        public static string FirstNonEmpty(params string[] args) => args.FirstOrDefault(x => !string.IsNullOrWhiteSpace(x));\n\n        public static bool AnyEmpty(params string[] args) => args.Any(x => string.IsNullOrWhiteSpace(x));\n\n        public static string LimitString(string str, int length) => str?.Substring(0, Math.Min(str.Length, length));\n\n        public static IEnumerable&lt;string> SplitSizes(string str, params int[] sizes)\n        {\n            var start = 0;\n            return sizes.Select(s => {\n                if (start + s > str.Length) return \"\";\n                var result = str.Substring(start, s);\n                start += s;\n                return result;\n            });\n        }    \n\n        public static string JoinUrl(string baseUrl, params string[] parts)\n        {\n            var partList = new List&lt;string>();\n            partList.Add(baseUrl.TrimEnd('\/'));\n            foreach (string part in parts)\n            {\n                if (!String.IsNullOrEmpty(part)) partList.Add(part);\n            }\n            return String.Join(\"\/\", partList);\n        }\n\n        private static readonly Regex nonAsciiRegex = new Regex(\"[^ -~]+\", RegexOptions.Compiled);\n        public static string ReplaceNonAsciiChars(string input)\n        {\n            if (string.IsNullOrWhiteSpace(input))\n                return input;\n            return nonAsciiRegex.Replace(input, \"\");\n        }\n\n\t\tpublic static string ShortenText(string caption, int length)\n\t\t{\n\t\t\tif (string.IsNullOrEmpty(caption) || length &lt;= 0)\n\t\t\t\treturn \"\";\n\n            if (caption.Length &lt;= length)\n                return caption;\n            \n            int count = length - 5;\n            int lastIndex = caption.LastIndexOfAny(new char[] { ' ', ',', '.', '-' }, length - 1, count);\n            if (lastIndex >= 0)\n                return caption.Remove(lastIndex) + \" ...\";\n            else\n                return caption.Remove(length - 4) + \" ...\";\n        }\n\n\t\tpublic static string ShortenTextSimple(string caption, int length)\n\t\t{\n\t\t\tif (string.IsNullOrEmpty(caption) || length &lt;= 0)\n\t\t\t\treturn \"\";\n            if (caption.Length &lt;= length)\n                return caption;\n\n            return caption.Remove(length - 3) + \"...\";\n        }\n\n        public static List&lt;string> SplitString(string str, int chunkSize)\n        {\n            if (string.IsNullOrWhiteSpace(str))\n                str = \"\";\n\n            var chunks = new List&lt;string>(); ;\n            int stringLength = str.Length;\n            for (int i = 0; i &lt; stringLength; i += chunkSize)\n            {\n                if (i + chunkSize > stringLength) chunkSize = stringLength - i;\n                chunks.Add(str.Substring(i, chunkSize));\n            }\n            if (chunks.Count == 0)\n                chunks.Add(\"\");\n\n            return chunks;\n        }\n\n        public static string Right(string value, int length) => value.Substring(value.Length - length);\n\n        public static string UppercaseFirst(string str)\n        {\n            if (string.IsNullOrEmpty(str)) \n                return str;\n            return char.ToUpper(str[0]) + str.Substring(1);\n        }\n\n        public static bool ContainsIc(string src, string item) => HasString(src, item);\n\n\t\tpublic static bool HasString(string src, string item)\n\t\t{\n\t\t\treturn src?.IndexOf(item ?? \"\", StringComparison.OrdinalIgnoreCase) >= 0;\n\t\t}\n\n        public static string Repeat(string s, int count) => new StringBuilder(s.Length * count).Insert(0, s, count).ToString();\n\t\t\n        private static readonly string[] trueValues = { \"true\", \"1\", \"y\", \"yes\" }; \/\/ add your language yes value here\n        public static bool StringToBool(string val) => trueValues.Contains(val?.Trim(), StringComparer.OrdinalIgnoreCase);\n\n        public static string StreamToString(Stream stream)\n        {\n            if (stream.CanSeek) stream.Position = 0;\n            return new StreamReader(stream).ReadToEnd();\n        }\t\t\n        \n        public static string GetLastCharacters(string s, int count) => string.Concat($\"{s}\".Trim().TakeLast(count));\n        \n        public static bool AreFirstNCharsEqual(string a, string b, int n)\n        {\n            if (string.IsNullOrEmpty(a) &amp;&amp; string.IsNullOrEmpty(b)) return false;\n            if (a?.Length &lt; n || b?.Length &lt; n) return false;\n            return string.Equals(a.Substring(0, n), b.Substring(0, n), StringComparison.OrdinalIgnoreCase);\n        }\n        \n        public static string RemoveDiacritics(string text)\n        {\n            var normalizedString = text.Normalize(NormalizationForm.FormD);\n            var stringBuilder = new StringBuilder();\n            foreach (var c in normalizedString)\n            {\n                var unicodeCategory = CharUnicodeInfo.GetUnicodeCategory(c);\n                if (unicodeCategory != UnicodeCategory.NonSpacingMark)\n                {\n                    stringBuilder.Append(c);\n                }\n            }\n            return stringBuilder.ToString().Normalize(NormalizationForm.FormC);\n        }\n        \n        private static readonly Regex LineRegex = new Regex(@\"\\r?\\n|\\r\", RegexOptions.Compiled);\n\n        public static string[] GetLines(string s) => LineRegex.Split(s);\n        \n        private static readonly Regex WhiteSpaceRegex = new Regex(@\"\\s+\", RegexOptions.Compiled);\n\n        public static string[] SplitWhiteSpace(string s) => WhiteSpaceRegex.Split(s);\n\n\n        public static string RemoveEmptyLines(string text)\n        {\n            return Regex.Replace(text, @\"^\\s*$[\\r\\n]*\", string.Empty, RegexOptions.Multiline);\n        }\n        \n        private static readonly Regex MultiLineRegex = new Regex(@\"^\\s*$[\\r\\n]*\", RegexOptions.Multiline | RegexOptions.Compiled);\n        public static string RemoveEmptyLines(string text) => MultiLineRegex.Replace(text, string.Empty);\n        public static string RemoveEmptyLinesWithSingle(string text) => MultiLineRegex.Replace(text, \"\\n\");\n\n        public static string AddDotsToFirstLineWhenMultiline(string v)\n        {\n            var lines = GetLines(v.Trim()).Where(x => !string.IsNullOrWhiteSpace(v)).ToList();\n            if (lines.Count > 1)\n                lines[0] = $\"{lines[0]}...\";\n            return string.Join(Environment.NewLine, lines);\n        }\n        \n        public static List&lt;int> GetNumbersFromString(string input) => regexDigitGroups.Matches(input)?.Select(x => x.Value.TrimStart('0')).Select(int.Parse).ToList() ?? [];\n\n        private static Regex regexDigitGroups = new(@\"\\d+\", RegexOptions.Compiled);\n        \n        public static string CombinedId(params object[] args) => string.Join(\"-\", args.Select(x => $\"{Convert.ToBase64String(Encoding.UTF8.GetBytes($\"{x}\"))}\"));\n        public static List&lt;string> ParseCombinedId(string id) => $\"{id}\".Split(\"-\").Select(Convert.FromBase64String).Select(Encoding.UTF8.GetString).ToList();\n        public static bool HasValue(string s) => !HasNoValue(s);\n        public static bool HasNoValue(string s) => string.IsNullOrWhiteSpace(s);\n        public static IEnumerable&lt;string> SelectNonEmpty(params string[] arr) => arr.Where(HasValue).ToList();\n        public static string JoinNonEmpty(string sep, params string[] arr) => string.Join(sep, SelectNonEmpty(arr));\n    }\n}\n<\/pre><\/div>\n\n\n\n<div style=\"height: 250px; position:relative; margin-bottom: 50px;\" class=\"wp-block-simple-code-block-ace\"><pre class=\"wp-block-simple-code-block-ace\" style=\"position:absolute;top:0;right:0;bottom:0;left:0\" data-mode=\"csharp\" data-theme=\"monokai\" data-fontsize=\"14\" data-lines=\"Infinity\" data-showlines=\"true\" data-copy=\"false\">    public enum SurroundWith\n    {\n        Quote,\n        SingleQuote,\n        Parentheses,\n        CurlyBraces,\n        SquareBrackets,\n        AngleBrackets,\n        Space\n    }\n    \n    public class StringHelpers\n    {\n        \/\/ ...\n    \n        private static readonly Dictionary&lt;SurroundWith, (string open, string close)> SurroundMap = new()\n        {\n            [SurroundWith.Quote] = (\"\\\"\", \"\\\"\"),\n            [SurroundWith.SingleQuote] = (\"'\", \"'\"),\n            [SurroundWith.Parentheses] = (\"(\", \")\"),\n            [SurroundWith.CurlyBraces] = (\"{\", \"}\"),\n            [SurroundWith.SquareBrackets] = (\"[\", \"]\"),\n            [SurroundWith.AngleBrackets] = (\"&lt;\", \">\"),\n            [SurroundWith.Space] = (\" \", \" \")\n        };\n        \/\/\/ &lt;summary>\n        \/\/\/ Omringt de tekst met tekens als deze niet leeg is.\n        \/\/\/ &lt;\/summary>\n        public static string SurroundIfNonEmpty(SurroundWith surroundWith, string text)\n        {\n            if (HasNoValue(text))\n                return string.Empty;\n\n            var (open, close) = SurroundMap[surroundWith];\n            return $\"{open}{text}{close}\";\n        }\n    }\n        <\/pre><\/div>\n","protected":false},"excerpt":{"rendered":"","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"inline_featured_image":false,"footnotes":""},"categories":[6,4,1],"tags":[],"class_list":["post-2835","post","type-post","status-publish","format-standard","hentry","category-dotnet","category-programming","category-uncategorized"],"_links":{"self":[{"href":"https:\/\/solidt.eu\/site\/wp-json\/wp\/v2\/posts\/2835","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/solidt.eu\/site\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/solidt.eu\/site\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/solidt.eu\/site\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/solidt.eu\/site\/wp-json\/wp\/v2\/comments?post=2835"}],"version-history":[{"count":30,"href":"https:\/\/solidt.eu\/site\/wp-json\/wp\/v2\/posts\/2835\/revisions"}],"predecessor-version":[{"id":9882,"href":"https:\/\/solidt.eu\/site\/wp-json\/wp\/v2\/posts\/2835\/revisions\/9882"}],"wp:attachment":[{"href":"https:\/\/solidt.eu\/site\/wp-json\/wp\/v2\/media?parent=2835"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/solidt.eu\/site\/wp-json\/wp\/v2\/categories?post=2835"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/solidt.eu\/site\/wp-json\/wp\/v2\/tags?post=2835"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}