i have a label
control in windows form
. i want to display full text in the label
. condition is like this:
if possible split by full word, without hyphen(-).
So far i have reach till below code:
private void Form1_Load(object sender, EventArgs e)
{
string strtext = "This is a very long text. this will come in one line.This is a very long text. this will come in one line.";
if (strtext.Length > 32)
{
IEnumerable<string> strEnum = Split(strtext, 32);
label1.Text =string.Join("-\n", strEnum);
}
}
static IEnumerable<string> Split(string str, int chunkSize)
{
return Enumerable.Range(0, str.Length / chunkSize)
.Select(i => str.Substring(i * chunkSize, chunkSize));
}
but issue is that the last line is not displaying entirely because its splitting by 32 character.
Is there another way to achieve this?
I don't know if you will accept an answer that doesn't use linq, but this is simple:
string SplitOnWholeWord(string toSplit, int maxLineLength)
{
StringBuilder sb = new StringBuilder();
string[] parts = toSplit.Split();
string line = string.Empty;
foreach(string s in parts)
{
if(s.Length > 32)
{
string p = s;
while(p.Length > 32)
{
int addedChars = 32 - line.Length;
line = string.Join(" ", line, p.Substring(0, addedChars));
sb.AppendLine(line);
p = p.Substring(addedChars);
line = string.Empty;
}
line = p;
}
else
{
if(line.Length + s.Length > maxLineLength)
{
sb.AppendLine(line);
line = string.Empty;
}
line = (line.Length > 0 ? string.Join(" ", line, s) : s);
}
}
sb.Append(line.Trim());
return sb.ToString();
}
Call with
string result = SplitOnWholeWord(strtext, 32);
It is possible to transform this in an extension method easily:
Put the code above in a separate file and create a static class
public static class StringExtensions
{
public static string SplitOnWholeWord(this string toSplit, int maxLineLength)
{
// same code as above.....
}
}
and call it in this way:
string result = strtext.SplitOnWholeWord(32);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With