1

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.

3 Answers 3

2

Would a CSS solution work better?

word-wrap:break-word;

example: http://jsfiddle.net/45Fq4/

Sign up to request clarification or add additional context in comments.

6 Comments

I know it doesn't answer the regex question specifically, I just think maybe the question is assuming the wrong solution to the problem.
I'd say it answers the problem as stated in the first sentence. You're just doing it in a different way but in what looks like the best way.
Please don't link w3schools. Try MDN instead.
@Romoku: You shouldn't say that without references for why. I've seen them before myself but for anybody that hasn't you're just sounding silly. :)
no that doesn't work..I guess cause I didnt mention that this is a mobile view so that would cause more problems then fix
|
1

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);

2 Comments

So how do I change that line of code I put in my question, as I said I am not good with regex: Regex.Replace(words, @"\S{20}", "$1" + Environment.NewLine);
I've added in an example and clarified my first line which should indeed have () to capture the contents of the match for use with the $1.
0

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.