Skip to content

Commit a8f5117

Browse files
PromoFauxrgomez90
andcommitted
Add @rgomez90 suggestion from #19 (comment)
Co-authored-by: Rafael Gomez <rgomez90@users.noreply.github.com> Signed-off-by: Adam Warner <me@adamwarner.co.uk>
1 parent 21905dc commit a8f5117

File tree

1 file changed

+17
-27
lines changed

1 file changed

+17
-27
lines changed

Matterhook.NET.MatterhookClient/StringSplitter.cs

Lines changed: 17 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -20,56 +20,46 @@ public static IEnumerable<string> SplitTextIntoChunks(string str, int maxChunkSi
2020
{
2121
if (string.IsNullOrEmpty(str)) throw new ArgumentException("Text can't be null or empty.", nameof(str));
2222
if (maxChunkSize < 1) throw new ArgumentException("Max. chunk size must be at least 1 char.", nameof(maxChunkSize));
23-
24-
return SplitTextIntoChunks2();
25-
26-
IEnumerable<string> SplitTextIntoChunks2()
23+
if (str.Length < maxChunkSize) return new List<string> { str };
24+
if (preserveWords)
2725
{
28-
if (str.Length < maxChunkSize)
29-
{
30-
yield return str;
31-
}
32-
else if (preserveWords)
33-
{
34-
//Less Simple
35-
foreach (var chunk in SplitTextBySizePreservingWords(str, maxChunkSize))
36-
yield return chunk;
37-
}
38-
else
39-
{
40-
//Simple
41-
foreach (var chunk in SplitTextBySize(str, maxChunkSize))
42-
yield return chunk;
43-
}
26+
return SplitTextBySizePreservingWords(str, maxChunkSize);
27+
}
28+
else
29+
{
30+
return SplitTextBySize(str, maxChunkSize);
4431
}
4532
}
4633

4734
private static IEnumerable<string> SplitTextBySize(string str, int maxChunkSize)
4835
{
49-
if (str.Length < maxChunkSize) yield return str;
36+
if (str.Length < maxChunkSize) return new List<string> { str };
37+
var list = new List<string>();
5038
for (var i = 0; i < str.Length; i += maxChunkSize)
5139
{
52-
yield return str.Substring(i, Math.Min(maxChunkSize, str.Length - i));
40+
list.Add(str.Substring(i, Math.Min(maxChunkSize, str.Length - i)));
5341
}
42+
return list;
5443
}
5544

5645
private static IEnumerable<string> SplitTextBySizePreservingWords(string str, int maxChunkSize)
5746
{
58-
if (str.Length < maxChunkSize) yield return str;
47+
if (str.Length < maxChunkSize) return new List<string> { str };
5948
var words = str.Split(' ');
6049
var tempString = new StringBuilder("");
61-
50+
var list = new List<string>();
6251
foreach (var word in words)
6352
{
6453
if (word.Length + tempString.Length + 1 > maxChunkSize)
6554
{
66-
yield return tempString.ToString();
55+
list.Add(tempString.ToString());
6756
tempString.Clear();
6857
}
69-
7058
tempString.Append(tempString.Length > 0 ? " " + word : word);
7159
}
72-
yield return tempString.ToString();
60+
if (tempString.Length >= 1)
61+
list.Add(tempString.ToString());
62+
return list;
7363
}
7464
}
7565
}

0 commit comments

Comments
 (0)