I have a field that is displayed inside a div and the problem is that it doesn't break line if a user puts in a string thats longer then the number of characters that can fit outside the line within a div, it basically stretches outside the div. How can I insert a space in every word 'thats in a string' that has a seuqence of 20 characters or more without a space between . For example, now I am doing something like this
string words
Regex.Replace(words, "(.{" + 20 + "})", "$1" + Environment.NewLine);
But that just inserts a line break at every 20 character oppose to a sequence without a space. I am really not that good with regular expressions so the code above is something I found.
To solve this with regex you could use @"(\\S{20})"
as your pattern.
\\S will match any non-whitespace character which I believe fits your criteria since it will then only work if it finds 20 or more non-whitespace characters in a row.
Example usage is:
string words = "It should break after \"t\": abcdefghijklmnopqrstuvwxyz";
string output = Regex.Replace(words, @"(\S{20})", "$1" + Environment.NewLine);
this code worked for me:
string words
string outputwords = words;
int CharsWithoutSpace = 0;
for (int i = 0; i < outputwords.Length; i++)
{
if (outputwords[i] == ' ')
{
CharsWithoutSpace = 0;
}
else
{
CharsWithoutSpace++;
if (CharsWithoutSpace >= 20)
{
outputwords = outputwords.Insert(i + 1, Environment.NewLine);
CharsWithoutSpace = 0;
}
}
}
Console.WriteLine(outputwords);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.